diff --git a/test-output/cases/echo_bitarray/build/dev/erlang/echo_bitarray/_gleam_artefacts/echo_bitarray@@main.erl b/test-output/cases/echo_bitarray/build/dev/erlang/echo_bitarray/_gleam_artefacts/echo_bitarray@@main.erl deleted file mode 100644 index 94411f01f4a..00000000000 --- a/test-output/cases/echo_bitarray/build/dev/erlang/echo_bitarray/_gleam_artefacts/echo_bitarray@@main.erl +++ /dev/null @@ -1,99 +0,0 @@ --module('echo_bitarray@@main'). --export([run/1]). - --define(red, "\e[31;1m"). --define(grey, "\e[90m"). --define(reset_color, "\e[39m"). --define(reset_all, "\e[0m"). - -run(Module) -> - io:setopts(standard_io, [binary, {encoding, utf8}]), - io:setopts(standard_error, [{encoding, utf8}]), - process_flag(trap_exit, true), - Pid = spawn_link(fun() -> run_module(Module) end), - receive - {'EXIT', Pid, {Reason, StackTrace}} -> - print_error(exit, Reason, StackTrace), - init:stop(1) - end. - -run_module(Module) -> - try - {ok, _} = application:ensure_all_started('echo_bitarray'), - erlang:process_flag(trap_exit, false), - Module:main(), - erlang:halt(0) - catch - Class:Reason:StackTrace -> - print_error(Class, Reason, StackTrace), - init:stop(1) - end. - -print_error(Class, Error, Stacktrace) -> - Printed = [ - ?red, "runtime error", ?reset_color, ": ", error_class(Class, Error), ?reset_all, - "\n\n", - error_message(Error), - "\n\n", - error_details(Class, Error), - "stacktrace:\n", - [error_frame(Line) || Line <- refine_first(Error, Stacktrace)] - ], - io:format(standard_error, "~ts~n", [Printed]). - -refine_first(#{gleam_error := _, line := L}, [{M, F, A, [{file, Fi} | _]} | S]) -> - [{M, F, A, [{file, Fi}, {line, L}]} | S]; -refine_first(_, S) -> - S. - -error_class(_, #{gleam_error := panic}) -> "panic"; -error_class(_, #{gleam_error := todo}) -> "todo"; -error_class(_, #{gleam_error := let_assert}) -> "let assert"; -error_class(Class, _) -> ["Erlang ", atom_to_binary(Class)]. - -error_message(#{gleam_error := _, message := M}) -> - M; -error_message(undef) -> - <<"A function was called but it did not exist."/utf8 >>; -error_message({case_clause, _}) -> - <<"No pattern matched in an Erlang case expression."/utf8>>; -error_message({badmatch, _}) -> - <<"An Erlang assignment pattern did not match."/utf8>>; -error_message(function_clause) -> - <<"No Erlang function clause matched the arguments it was called with."/utf8>>; -error_message(_) -> - <<"An error occurred outside of Gleam."/utf8>>. - -error_details(_, #{gleam_error := let_assert, value := V}) -> - ["unmatched value:\n ", print_term(V), $\n, $\n]; -error_details(_, {case_clause, V}) -> - ["unmatched value:\n ", print_term(V), $\n, $\n]; -error_details(_, {badmatch, V}) -> - ["unmatched value:\n ", print_term(V), $\n, $\n]; -error_details(_, #{gleam_error := _}) -> - []; -error_details(error, function_clause) -> - []; -error_details(error, undef) -> - []; -error_details(C, E) -> - ["erlang:", atom_to_binary(C), $(, print_term(E), $), $\n, $\n]. - -print_term(T) -> - try - gleam@string:inspect(T) - catch - _:_ -> io_lib:format("~p", [T]) - end. - -error_frame({?MODULE, _, _, _}) -> []; -error_frame({erl_eval, _, _, _}) -> []; -error_frame({init, _, _, _}) -> []; -error_frame({M, F, _, O}) -> - M1 = string:replace(atom_to_binary(M), "@", "/", all), - [" ", M1, $., atom_to_binary(F), error_frame_end(O), $\n]. - -error_frame_end([{file, Fi}, {line, L} | _]) -> - [?grey, $\s, Fi, $:, integer_to_binary(L), ?reset_all]; -error_frame_end(_) -> - [?grey, " unknown source", ?reset_all]. \ No newline at end of file diff --git a/test-output/cases/echo_bitarray/build/dev/erlang/echo_bitarray/_gleam_artefacts/gleam@@compile.erl b/test-output/cases/echo_bitarray/build/dev/erlang/echo_bitarray/_gleam_artefacts/gleam@@compile.erl deleted file mode 100644 index 3e0a645b737..00000000000 --- a/test-output/cases/echo_bitarray/build/dev/erlang/echo_bitarray/_gleam_artefacts/gleam@@compile.erl +++ /dev/null @@ -1,163 +0,0 @@ -#!/usr/bin/env escript --mode(compile). - -% TODO: Don't concurrently print warnings and errors -% TODO: Some tests - -main(_) -> compile_package_loop(). - -compile_package_loop() -> - case file:read_line(standard_io) of - eof -> ok; - {ok, Line} -> - Chars = unicode:characters_to_list(Line), - {ok, Tokens, _} = erl_scan:string(Chars), - {ok, {Lib, Out, Modules}} = erl_parse:parse_term(Tokens), - case compile_package(Lib, Out, Modules) of - ok -> io:put_chars("gleam-compile-result-ok\n"); - err -> io:put_chars("gleam-compile-result-error\n") - end, - compile_package_loop() - end. - -compile_package(Lib, Out, Modules) -> - IsElixirModule = fun(Module) -> - filename:extension(Module) =:= ".ex" - end, - {ElixirModules, ErlangModules} = lists:partition(IsElixirModule, Modules), - ok = configure_logging(), - ok = add_lib_to_erlang_path(Lib), - ok = filelib:ensure_dir([Out, $/]), - {ErlangOk, _ErlangBeams} = compile_erlang(ErlangModules, Out), - {ElixirOk, _ElixirBeams} = case ErlangOk of - true -> compile_elixir(ElixirModules, Out); - false -> {false, []} - end, - ok = del_lib_from_erlang_path(Lib), - case ErlangOk and ElixirOk of - true -> ok; - false -> err - end. - -compile_erlang(Modules, Out) -> - Workers = start_compiler_workers(Out), - ok = producer_loop(Modules, Workers), - collect_results({true, []}). - -collect_results(Acc = {Result, Beams}) -> - receive - {compiled, Beam} -> collect_results({Result, [Beam | Beams]}); - failed -> collect_results({false, Beams}) - after 0 -> Acc - end. - -producer_loop([], 0) -> - ok; -producer_loop([], Workers) -> - receive - {work_please, _} -> producer_loop([], Workers - 1) - end; -producer_loop([Module | Modules], Workers) -> - receive - {work_please, Worker} -> - erlang:send(Worker, {module, Module}), - producer_loop(Modules, Workers) - end. - -start_compiler_workers(Out) -> - Parent = self(), - NumSchedulers = erlang:system_info(schedulers), - SpawnWorker = fun(_) -> - erlang:spawn_link(fun() -> worker_loop(Parent, Out) end) - end, - lists:foreach(SpawnWorker, lists:seq(1, NumSchedulers)), - NumSchedulers. - -worker_loop(Parent, Out) -> - Options = [report_errors, report_warnings, debug_info, {outdir, Out}], - erlang:send(Parent, {work_please, self()}), - receive - {module, Module} -> - log({compiling, Module}), - case compile:file(Module, Options) of - {ok, ModuleName} -> - Beam = filename:join(Out, ModuleName) ++ ".beam", - Message = {compiled, Beam}, - log(Message), - erlang:send(Parent, Message); - error -> - log({failed, Module}), - erlang:send(Parent, failed) - end, - worker_loop(Parent, Out) - end. - -compile_elixir(Modules, Out) -> - Error = [ - "The program elixir was not found. Is it installed?", - $\n, - "Documentation for installing Elixir can be viewed here:", - $\n, - "https://elixir-lang.org/install.html" - ], - case Modules of - [] -> {true, []}; - _ -> - log({starting, "compiler.app"}), - ok = application:start(compiler), - log({starting, "elixir.app"}), - case application:start(elixir) of - ok -> do_compile_elixir(Modules, Out); - _ -> - io:put_chars(standard_error, [Error, $\n]), - {false, []} - end - end. - -do_compile_elixir(Modules, Out) -> - ModuleBins = lists:map(fun(Module) -> - log({compiling, Module}), - list_to_binary(Module) - end, Modules), - OutBin = list_to_binary(Out), - Options = [{dest, OutBin}], - % Silence "redefining module" warnings. - % Compiled modules in the build directory are added to the code path. - % These warnings result from recompiling loaded modules. - % TODO: This line can likely be removed if/when the build directory is cleaned before every compilation. - 'Elixir.Code':compiler_options([{ignore_module_conflict, true}]), - case 'Elixir.Kernel.ParallelCompiler':compile_to_path(ModuleBins, OutBin, Options) of - {ok, ModuleAtoms, _} -> - ToBeam = fun(ModuleAtom) -> - Beam = filename:join(Out, atom_to_list(ModuleAtom)) ++ ".beam", - log({compiled, Beam}), - Beam - end, - {true, lists:map(ToBeam, ModuleAtoms)}; - {error, Errors, _} -> - % Log all filenames associated with modules that failed to compile. - % Note: The compiler prints compilation errors upon encountering them. - ErrorFiles = lists:usort([File || {File, _, _} <- Errors]), - Log = fun(File) -> - log({failed, binary_to_list(File)}) - end, - lists:foreach(Log, ErrorFiles), - {false, []}; - _ -> {false, []} - end. - -add_lib_to_erlang_path(Lib) -> - code:add_paths(filelib:wildcard([Lib, "/*/ebin"])). - -del_lib_from_erlang_path(Lib) -> - code:del_paths(filelib:wildcard([Lib, "/*/ebin"])). - -configure_logging() -> - Enabled = os:getenv("GLEAM_LOG") /= false, - persistent_term:put(gleam_logging_enabled, Enabled). - -log(Term) -> - case persistent_term:get(gleam_logging_enabled) of - true -> erlang:display(Term), ok; - false -> ok - end. diff --git a/test-output/cases/echo_bitarray/build/dev/erlang/echo_bitarray/_gleam_artefacts/main.cache b/test-output/cases/echo_bitarray/build/dev/erlang/echo_bitarray/_gleam_artefacts/main.cache deleted file mode 100644 index 4d829614923..00000000000 Binary files a/test-output/cases/echo_bitarray/build/dev/erlang/echo_bitarray/_gleam_artefacts/main.cache and /dev/null differ diff --git a/test-output/cases/echo_bitarray/build/dev/erlang/echo_bitarray/_gleam_artefacts/main.cache_meta b/test-output/cases/echo_bitarray/build/dev/erlang/echo_bitarray/_gleam_artefacts/main.cache_meta deleted file mode 100644 index b65a5e9a436..00000000000 Binary files a/test-output/cases/echo_bitarray/build/dev/erlang/echo_bitarray/_gleam_artefacts/main.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_bitarray/build/dev/erlang/echo_bitarray/_gleam_artefacts/main.cache_warnings b/test-output/cases/echo_bitarray/build/dev/erlang/echo_bitarray/_gleam_artefacts/main.cache_warnings deleted file mode 100644 index 1b1cb4d44c5..00000000000 Binary files a/test-output/cases/echo_bitarray/build/dev/erlang/echo_bitarray/_gleam_artefacts/main.cache_warnings and /dev/null differ diff --git a/test-output/cases/echo_bitarray/build/dev/erlang/echo_bitarray/_gleam_artefacts/main.erl b/test-output/cases/echo_bitarray/build/dev/erlang/echo_bitarray/_gleam_artefacts/main.erl deleted file mode 100644 index ff40f0f2098..00000000000 --- a/test-output/cases/echo_bitarray/build/dev/erlang/echo_bitarray/_gleam_artefacts/main.erl +++ /dev/null @@ -1,196 +0,0 @@ --module(main). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([target_specific/0, main/0]). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_bitarray/src/main.gleam", 8). --spec target_specific() -> bitstring(). -target_specific() -> - echo(<<1, 2, 3:2>>, "src/main.gleam", 10). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_bitarray/src/main.gleam", 1). --spec main() -> bitstring(). -main() -> - echo(<<>>, "src/main.gleam", 2), - echo(<<1, 2, 3>>, "src/main.gleam", 3), - target_specific(). - --define(is_lowercase_char(X), (X > 96 andalso X < 123)). --define(is_underscore_char(X), (X == 95)). --define(is_digit_char(X), (X > 47 andalso X < 58)). --define(could_be_record(Tuple), - erlang:is_tuple(Tuple) andalso - erlang:is_atom(erlang:element(1, Tuple)) andalso - erlang:element(1, Tuple) =/= false andalso - erlang:element(1, Tuple) =/= true andalso - erlang:element(1, Tuple) =/= nil -). --define(is_atom_char(C), - (?is_lowercase_char(C) orelse - ?is_underscore_char(C) orelse - ?is_digit_char(C)) -). - --define(grey, "\e[90m"). --define(reset_color, "\e[39m"). - -echo(Value, File, Line) -> - StringLine = erlang:integer_to_list(Line), - StringValue = echo@inspect(Value), - io:put_chars( - standard_error, - [?grey, File, $:, StringLine, ?reset_color, $\n, StringValue, $\n] - ), - Value. - -echo@inspect(Value) -> - case Value of - nil -> "Nil"; - true -> "True"; - false -> "False"; - Int when erlang:is_integer(Int) -> erlang:integer_to_list(Int); - Float when erlang:is_float(Float) -> io_lib_format:fwrite_g(Float); - Binary when erlang:is_binary(Binary) -> inspect@binary(Binary); - Bits when erlang:is_bitstring(Bits) -> inspect@bit_array(Bits); - Atom when erlang:is_atom(Atom) -> inspect@atom(Atom); - List when erlang:is_list(List) -> inspect@list(List); - Map when erlang:is_map(Map) -> inspect@map(Map); - Record when ?could_be_record(Record) -> inspect@record(Record); - Tuple when erlang:is_tuple(Tuple) -> inspect@tuple(Tuple); - Function when erlang:is_function(Function) -> inspect@function(Function); - Any -> ["//erl(", io_lib:format("~p", [Any]), ")"] - end. - -inspect@bit_array(Bits) -> - Pieces = inspect@bit_array_pieces(Bits, []), - Inner = lists:join(", ", lists:reverse(Pieces)), - ["<<", Inner, ">>"]. - -inspect@bit_array_pieces(Bits, Acc) -> - case Bits of - <<>> -> - Acc; - <> -> - inspect@bit_array_pieces(Rest, [erlang:integer_to_binary(Byte) | Acc]); - _ -> - Size = erlang:bit_size(Bits), - <> = Bits, - SizeString = [":size(", erlang:integer_to_binary(Size), ")"], - Piece = [erlang:integer_to_binary(RemainingBits), SizeString], - [Piece | Acc] - end. - -inspect@binary(Binary) -> - case inspect@maybe_utf8_string(Binary, <<>>) of - {ok, InspectedUtf8String} -> - InspectedUtf8String; - {error, not_a_utf8_string} -> - Segments = [erlang:integer_to_list(X) || <> <= Binary], - ["<<", lists:join(", ", Segments), ">>"] - end. - -inspect@atom(Atom) -> - Binary = erlang:atom_to_binary(Atom), - case inspect@maybe_gleam_atom(Binary, none, <<>>) of - {ok, Inspected} -> Inspected; - {error, _} -> ["atom.create_from_string(\"", Binary, "\")"] - end. - -inspect@list(List) -> - case inspect@proper_or_improper_list(List) of - {proper, Elements} -> ["[", Elements, "]"]; - {improper, Elements} -> ["//erl([", Elements, "])"] - end. - -inspect@map(Map) -> - Fields = [ - [<<"#(">>, echo@inspect(Key), <<", ">>, echo@inspect(Value), <<")">>] - || {Key, Value} <- maps:to_list(Map) - ], - ["dict.from_list([", lists:join(", ", Fields), "])"]. - -inspect@record(Record) -> - [Atom | ArgsList] = erlang:tuple_to_list(Record), - Args = lists:join(", ", lists:map(fun echo@inspect/1, ArgsList)), - [echo@inspect(Atom), "(", Args, ")"]. - -inspect@tuple(Tuple) -> - Elements = lists:map(fun echo@inspect/1, erlang:tuple_to_list(Tuple)), - ["#(", lists:join(", ", Elements), ")"]. - -inspect@function(Function) -> - {arity, Arity} = erlang:fun_info(Function, arity), - ArgsAsciiCodes = lists:seq($a, $a + Arity - 1), - Args = lists:join(", ", lists:map(fun(Arg) -> <> end, ArgsAsciiCodes)), - ["//fn(", Args, ") { ... }"]. - -inspect@maybe_utf8_string(Binary, Acc) -> - case Binary of - <<>> -> - {ok, <<$", Acc/binary, $">>}; - <> -> - Escaped = inspect@escape_grapheme(First), - inspect@maybe_utf8_string(Rest, <>); - _ -> - {error, not_a_utf8_string} - end. - -inspect@escape_grapheme(Char) -> - case Char of - $" -> <<$\\, $">>; - $\\ -> <<$\\, $\\>>; - $\r -> <<$\\, $r>>; - $\n -> <<$\\, $n>>; - $\t -> <<$\\, $t>>; - $\f -> <<$\\, $f>>; - X when X > 126, X < 160 -> inspect@convert_to_u(X); - X when X < 32 -> inspect@convert_to_u(X); - Other -> <> - end. - -inspect@convert_to_u(Code) -> - erlang:list_to_binary(io_lib:format("\\u{~4.16.0B}", [Code])). - -inspect@proper_or_improper_list(List) -> - case List of - [] -> - {proper, []}; - [First] -> - {proper, [echo@inspect(First)]}; - [First | Rest] when erlang:is_list(Rest) -> - {Kind, Inspected} = inspect@proper_or_improper_list(Rest), - {Kind, [echo@inspect(First), ", " | Inspected]}; - [First | ImproperRest] -> - {improper, [echo@inspect(First), " | ", echo@inspect(ImproperRest)]} - end. - -inspect@maybe_gleam_atom(Atom, PrevChar, Acc) -> - case {Atom, PrevChar} of - {<<>>, none} -> - {error, nil}; - {<>, none} when ?is_digit_char(First) -> - {error, nil}; - {<<"_", _/binary>>, none} -> - {error, nil}; - {<<"_">>, _} -> - {error, nil}; - {<<"_", _/binary>>, $_} -> - {error, nil}; - {<>, _} when not ?is_atom_char(First) -> - {error, nil}; - {<>, none} -> - inspect@maybe_gleam_atom(Rest, First, <>); - {<<"_", Rest/binary>>, _} -> - inspect@maybe_gleam_atom(Rest, $_, Acc); - {<>, $_} -> - inspect@maybe_gleam_atom(Rest, First, <>); - {<>, _} -> - inspect@maybe_gleam_atom(Rest, First, <>); - {<<>>, _} -> - {ok, Acc}; - _ -> - erlang:throw({gleam_error, echo, Atom, PrevChar, Acc}) - end. - -inspect@uppercase(X) -> X - 32. - diff --git a/test-output/cases/echo_bitarray/build/dev/erlang/echo_bitarray/ebin/echo_bitarray.app b/test-output/cases/echo_bitarray/build/dev/erlang/echo_bitarray/ebin/echo_bitarray.app deleted file mode 100644 index 2052d6d7595..00000000000 --- a/test-output/cases/echo_bitarray/build/dev/erlang/echo_bitarray/ebin/echo_bitarray.app +++ /dev/null @@ -1,7 +0,0 @@ -{application, echo_bitarray, [ - {vsn, "1.0.0"}, - {applications, []}, - {description, ""}, - {modules, [main]}, - {registered, []} -]}. diff --git a/test-output/cases/echo_bitarray/build/dev/erlang/gleam_version b/test-output/cases/echo_bitarray/build/dev/erlang/gleam_version deleted file mode 100644 index 3e1ad720b13..00000000000 --- a/test-output/cases/echo_bitarray/build/dev/erlang/gleam_version +++ /dev/null @@ -1 +0,0 @@ -1.5.0 \ No newline at end of file diff --git a/test-output/cases/echo_bitarray/build/dev/javascript/echo_bitarray/_gleam_artefacts/main.cache b/test-output/cases/echo_bitarray/build/dev/javascript/echo_bitarray/_gleam_artefacts/main.cache deleted file mode 100644 index 4715825a785..00000000000 Binary files a/test-output/cases/echo_bitarray/build/dev/javascript/echo_bitarray/_gleam_artefacts/main.cache and /dev/null differ diff --git a/test-output/cases/echo_bitarray/build/dev/javascript/echo_bitarray/_gleam_artefacts/main.cache_meta b/test-output/cases/echo_bitarray/build/dev/javascript/echo_bitarray/_gleam_artefacts/main.cache_meta deleted file mode 100644 index b65a5e9a436..00000000000 Binary files a/test-output/cases/echo_bitarray/build/dev/javascript/echo_bitarray/_gleam_artefacts/main.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_bitarray/build/dev/javascript/echo_bitarray/_gleam_artefacts/main.cache_warnings b/test-output/cases/echo_bitarray/build/dev/javascript/echo_bitarray/_gleam_artefacts/main.cache_warnings deleted file mode 100644 index 1b1cb4d44c5..00000000000 Binary files a/test-output/cases/echo_bitarray/build/dev/javascript/echo_bitarray/_gleam_artefacts/main.cache_warnings and /dev/null differ diff --git a/test-output/cases/echo_bitarray/build/dev/javascript/echo_bitarray/gleam.main.mjs b/test-output/cases/echo_bitarray/build/dev/javascript/echo_bitarray/gleam.main.mjs deleted file mode 100644 index e230911e646..00000000000 --- a/test-output/cases/echo_bitarray/build/dev/javascript/echo_bitarray/gleam.main.mjs +++ /dev/null @@ -1,2 +0,0 @@ -import { main } from "./main.mjs"; -main(); diff --git a/test-output/cases/echo_bitarray/build/dev/javascript/echo_bitarray/gleam.mjs b/test-output/cases/echo_bitarray/build/dev/javascript/echo_bitarray/gleam.mjs deleted file mode 100644 index 197cbbc35d4..00000000000 --- a/test-output/cases/echo_bitarray/build/dev/javascript/echo_bitarray/gleam.mjs +++ /dev/null @@ -1 +0,0 @@ -export * from "../prelude.mjs"; diff --git a/test-output/cases/echo_bitarray/build/dev/javascript/echo_bitarray/main.mjs b/test-output/cases/echo_bitarray/build/dev/javascript/echo_bitarray/main.mjs deleted file mode 100644 index 033e966819c..00000000000 --- a/test-output/cases/echo_bitarray/build/dev/javascript/echo_bitarray/main.mjs +++ /dev/null @@ -1,134 +0,0 @@ -import { - toBitArray, - BitArray as $BitArray, - List as $List, - UtfCodepoint as $UtfCodepoint, - CustomType as $CustomType, -} from "./gleam.mjs"; - -export function target_specific() { - return undefined; -} - -export function main() { - echo(toBitArray([]), "src/main.gleam", 2); - echo(toBitArray([1, 2, 3]), "src/main.gleam", 3); - return target_specific(); -} - -function echo(value, file, line) { - const grey = "\u001b[90m"; - const reset_color = "\u001b[39m"; - const file_line = `${file}:${line}`; - const string_value = echo$inspect(value); - - if (typeof process === "object" && process.stderr?.write) { - // If we're in Node.js, use `stderr` - const string = `${grey}${file_line}${reset_color}\n${string_value}\n`; - process.stderr.write(string); - } else if (typeof Deno === "object") { - // If we're in Deno, use `stderr` - const string = `${grey}${file_line}${reset_color}\n${string_value}\n`; - Deno.stderr.writeSync(new TextEncoder().encode(string)); - } else { - // Otherwise, use `console.log` - // The browser's console.log doesn't support ansi escape codes - const string = `${file_line}\n${string_value}`; - console.log(string); - } - - return value; -} - -function echo$inspectString(str) { - let new_str = '"'; - for (let i = 0; i < str.length; i++) { - let char = str[i]; - if (char == "\n") new_str += "\\n"; - else if (char == "\r") new_str += "\\r"; - else if (char == "\t") new_str += "\\t"; - else if (char == "\f") new_str += "\\f"; - else if (char == "\\") new_str += "\\\\"; - else if (char == '"') new_str += '\\"'; - else if (char < " " || (char > "~" && char < "\u{00A0}")) { - new_str += "\\u{" + char.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0") + "}"; - } else { - new_str += char; - } - } - new_str += '"'; - return new_str; -} - -function echo$inspectDict(map) { - let body = "dict.from_list(["; - let first = true; - map.forEach((value, key) => { - if (!first) body = body + ", "; - body = body + "#(" + echo$inspect(key) + ", " + echo$inspect(value) + ")"; - first = false; - }); - return body + "])"; -} - -function echo$inspectCustomType(record) { - const props = Object.keys(record) - .map((label) => { - const value = echo$inspect(record[label]); - return isNaN(parseInt(label)) ? `${label}: ${value}` : value; - }) - .join(", "); - return props ? `${record.constructor.name}(${props})` : record.constructor.name; -} - -function echo$inspectObject(v) { - const name = Object.getPrototypeOf(v)?.constructor?.name || "Object"; - const props = []; - for (const k of Object.keys(v)) { - props.push(`${echo$inspect(k)}: ${echo$inspect(v[k])}`); - } - const body = props.length ? " " + props.join(", ") + " " : ""; - const head = name === "Object" ? "" : name + " "; - return `//js(${head}{${body}})`; -} - -function echo$inspect(v) { - const t = typeof v; - if (v === true) return "True"; - if (v === false) return "False"; - if (v === null) return "//js(null)"; - if (v === undefined) return "Nil"; - if (t === "string") return echo$inspectString(v); - if (t === "bigint" || t === "number") return v.toString(); - if (Array.isArray(v)) return `#(${v.map(echo$inspect).join(", ")})`; - if (v instanceof $List) return `[${v.toArray().map(echo$inspect).join(", ")}]`; - if (v instanceof $UtfCodepoint) return `//utfcodepoint(${String.fromCodePoint(v.value)})`; - if (v instanceof $BitArray) return `<<${Array.from(v.buffer).join(", ")}>>`; - if (v instanceof $CustomType) return echo$inspectCustomType(v); - if (echo$isDict(v)) return echo$inspectDict(v); - if (v instanceof Set) return `//js(Set(${[...v].map(echo$inspect).join(", ")}))`; - if (v instanceof RegExp) return `//js(${v})`; - if (v instanceof Date) return `//js(Date("${v.toISOString()}"))`; - if (v instanceof Function) { - const args = []; - for (const i of Array(v.length).keys()) args.push(String.fromCharCode(i + 97)); - return `//fn(${args.join(", ")}) { ... }`; - } - return echo$inspectObject(v); -} - -function echo$isDict(value) { - try { - // We can only check if an object is a stdlib Dict if it is one of the - // project's dependencies. - // The `Dict` class is the default export of `stdlib/dict.mjs` - // that we import as `$stdlib$dict`. - return value instanceof $stdlib$dict.default; - } catch { - // If stdlib is not one of the project's dependencies then `$stdlib$dict` - // will not have been imported and the check will throw an exception meaning - // we can't check if something is actually a `Dict`. - return false; - } -} - diff --git a/test-output/cases/echo_bitarray/build/dev/javascript/gleam_version b/test-output/cases/echo_bitarray/build/dev/javascript/gleam_version deleted file mode 100644 index 3e1ad720b13..00000000000 --- a/test-output/cases/echo_bitarray/build/dev/javascript/gleam_version +++ /dev/null @@ -1 +0,0 @@ -1.5.0 \ No newline at end of file diff --git a/test-output/cases/echo_bitarray/build/dev/javascript/prelude.mjs b/test-output/cases/echo_bitarray/build/dev/javascript/prelude.mjs deleted file mode 100644 index d2adeef273f..00000000000 --- a/test-output/cases/echo_bitarray/build/dev/javascript/prelude.mjs +++ /dev/null @@ -1,455 +0,0 @@ -// Values marked with @internal are not part of the public API and may change -// without notice. - -export class CustomType { - withFields(fields) { - let properties = Object.keys(this).map((label) => - label in fields ? fields[label] : this[label], - ); - return new this.constructor(...properties); - } -} - -export class List { - static fromArray(array, tail) { - let t = tail || new Empty(); - for (let i = array.length - 1; i >= 0; --i) { - t = new NonEmpty(array[i], t); - } - return t; - } - - [Symbol.iterator]() { - return new ListIterator(this); - } - - toArray() { - return [...this]; - } - - // @internal - atLeastLength(desired) { - for (let _ of this) { - if (desired <= 0) return true; - desired--; - } - return desired <= 0; - } - - // @internal - hasLength(desired) { - for (let _ of this) { - if (desired <= 0) return false; - desired--; - } - return desired === 0; - } - - // @internal - countLength() { - let length = 0; - for (let _ of this) length++; - return length; - } -} - -// @internal -export function prepend(element, tail) { - return new NonEmpty(element, tail); -} - -export function toList(elements, tail) { - return List.fromArray(elements, tail); -} - -// @internal -class ListIterator { - #current; - - constructor(current) { - this.#current = current; - } - - next() { - if (this.#current instanceof Empty) { - return { done: true }; - } else { - let { head, tail } = this.#current; - this.#current = tail; - return { value: head, done: false }; - } - } -} - -export class Empty extends List {} - -export class NonEmpty extends List { - constructor(head, tail) { - super(); - this.head = head; - this.tail = tail; - } -} - -export class BitArray { - constructor(buffer) { - if (!(buffer instanceof Uint8Array)) { - throw "BitArray can only be constructed from a Uint8Array"; - } - this.buffer = buffer; - } - - // @internal - get length() { - return this.buffer.length; - } - - // @internal - byteAt(index) { - return this.buffer[index]; - } - - // @internal - floatFromSlice(start, end, isBigEndian) { - return byteArrayToFloat(this.buffer, start, end, isBigEndian); - } - - // @internal - intFromSlice(start, end, isBigEndian, isSigned) { - return byteArrayToInt(this.buffer, start, end, isBigEndian, isSigned); - } - - // @internal - binaryFromSlice(start, end) { - return new BitArray(this.buffer.slice(start, end)); - } - - // @internal - sliceAfter(index) { - return new BitArray(this.buffer.slice(index)); - } -} - -export class UtfCodepoint { - constructor(value) { - this.value = value; - } -} - -// @internal -export function toBitArray(segments) { - if (segments.length === 0) { - return new BitArray(new Uint8Array()); - } - - if (segments.length === 1) { - // When there is a single Uint8Array segment, pass it directly to the bit - // array constructor to avoid a copy - if (segments[0] instanceof Uint8Array) { - return new BitArray(segments[0]); - } - - return new BitArray(new Uint8Array(segments)); - } - - // Count the total number of bytes, and check if there are any Uint8Array - // segments - let bytes = 0; - let hasUint8ArraySegment = false; - for (const segment of segments) { - if (segment instanceof Uint8Array) { - bytes += segment.byteLength; - hasUint8ArraySegment = true; - } else { - bytes++; - } - } - - // If there aren't any Uint8Array segments then pass the segments array - // directly to the Uint8Array constructor - if (!hasUint8ArraySegment) { - return new BitArray(new Uint8Array(segments)); - } - - // Copy the segments into a Uint8Array - let u8Array = new Uint8Array(bytes); - let cursor = 0; - for (let segment of segments) { - if (segment instanceof Uint8Array) { - u8Array.set(segment, cursor); - cursor += segment.byteLength; - } else { - u8Array[cursor] = segment; - cursor++; - } - } - - return new BitArray(u8Array); -} - -// @internal -// Derived from this answer https://stackoverflow.com/questions/8482309/converting-javascript-integer-to-byte-array-and-back -export function sizedInt(value, size, isBigEndian) { - if (size < 0) { - return new Uint8Array(); - } - if (size % 8 != 0) { - const msg = `Bit arrays must be byte aligned on JavaScript, got size of ${size} bits`; - throw new globalThis.Error(msg); - } - - const byteArray = new Uint8Array(size / 8); - - // Convert negative number to two's complement representation - if (value < 0) { - value = 2 ** size + value; - } - - if (isBigEndian) { - for (let i = byteArray.length - 1; i >= 0; i--) { - const byte = value % 256; - byteArray[i] = byte; - value = (value - byte) / 256; - } - } else { - for (let i = 0; i < byteArray.length; i++) { - const byte = value % 256; - byteArray[i] = byte; - value = (value - byte) / 256; - } - } - - return byteArray; -} - -// @internal -export function byteArrayToInt(byteArray, start, end, isBigEndian, isSigned) { - let value = 0; - - // Read bytes as an unsigned integer value - if (isBigEndian) { - for (let i = start; i < end; i++) { - value = value * 256 + byteArray[i]; - } - } else { - for (let i = end - 1; i >= start; i--) { - value = value * 256 + byteArray[i]; - } - } - - if (isSigned) { - const byteSize = end - start; - - const highBit = 2 ** (byteSize * 8 - 1); - - // If the high bit is set and this is a signed integer, reinterpret as - // two's complement - if (value >= highBit) { - value -= highBit * 2; - } - } - - return value; -} - -// @internal -export function byteArrayToFloat(byteArray, start, end, isBigEndian) { - const view = new DataView(byteArray.buffer); - - const byteSize = end - start; - - if (byteSize === 8) { - return view.getFloat64(start, !isBigEndian); - } else if (byteSize === 4) { - return view.getFloat32(start, !isBigEndian); - } else { - const msg = `Sized floats must be 32-bit or 64-bit on JavaScript, got size of ${byteSize * 8} bits`; - throw new globalThis.Error(msg); - } -} - -// @internal -export function stringBits(string) { - return new TextEncoder().encode(string); -} - -// @internal -export function codepointBits(codepoint) { - return stringBits(String.fromCodePoint(codepoint.value)); -} - -// @internal -export function sizedFloat(float, size, isBigEndian) { - if (size !== 32 && size !== 64) { - const msg = `Sized floats must be 32-bit or 64-bit on JavaScript, got size of ${size} bits`; - throw new globalThis.Error(msg); - } - - const byteArray = new Uint8Array(size / 8); - - const view = new DataView(byteArray.buffer); - - if (size == 64) { - view.setFloat64(0, float, !isBigEndian); - } else if (size === 32) { - view.setFloat32(0, float, !isBigEndian); - } - - return byteArray; -} - -export class Result extends CustomType { - // @internal - static isResult(data) { - return data instanceof Result; - } -} - -export class Ok extends Result { - constructor(value) { - super(); - this[0] = value; - } - - // @internal - isOk() { - return true; - } -} - -export class Error extends Result { - constructor(detail) { - super(); - this[0] = detail; - } - - // @internal - isOk() { - return false; - } -} - -export function isEqual(x, y) { - let values = [x, y]; - - while (values.length) { - let a = values.pop(); - let b = values.pop(); - if (a === b) continue; - - if (!isObject(a) || !isObject(b)) return false; - let unequal = - !structurallyCompatibleObjects(a, b) || - unequalDates(a, b) || - unequalBuffers(a, b) || - unequalArrays(a, b) || - unequalMaps(a, b) || - unequalSets(a, b) || - unequalRegExps(a, b); - if (unequal) return false; - - const proto = Object.getPrototypeOf(a); - if (proto !== null && typeof proto.equals === "function") { - try { - if (a.equals(b)) continue; - else return false; - } catch {} - } - - let [keys, get] = getters(a); - for (let k of keys(a)) { - values.push(get(a, k), get(b, k)); - } - } - - return true; -} - -function getters(object) { - if (object instanceof Map) { - return [(x) => x.keys(), (x, y) => x.get(y)]; - } else { - let extra = object instanceof globalThis.Error ? ["message"] : []; - return [(x) => [...extra, ...Object.keys(x)], (x, y) => x[y]]; - } -} - -function unequalDates(a, b) { - return a instanceof Date && (a > b || a < b); -} - -function unequalBuffers(a, b) { - return ( - a.buffer instanceof ArrayBuffer && - a.BYTES_PER_ELEMENT && - !(a.byteLength === b.byteLength && a.every((n, i) => n === b[i])) - ); -} - -function unequalArrays(a, b) { - return Array.isArray(a) && a.length !== b.length; -} - -function unequalMaps(a, b) { - return a instanceof Map && a.size !== b.size; -} - -function unequalSets(a, b) { - return ( - a instanceof Set && (a.size != b.size || [...a].some((e) => !b.has(e))) - ); -} - -function unequalRegExps(a, b) { - return a instanceof RegExp && (a.source !== b.source || a.flags !== b.flags); -} - -function isObject(a) { - return typeof a === "object" && a !== null; -} - -function structurallyCompatibleObjects(a, b) { - if (typeof a !== "object" && typeof b !== "object" && (!a || !b)) - return false; - - let nonstructural = [Promise, WeakSet, WeakMap, Function]; - if (nonstructural.some((c) => a instanceof c)) return false; - - return a.constructor === b.constructor; -} - -// @internal -export function remainderInt(a, b) { - if (b === 0) { - return 0; - } else { - return a % b; - } -} - -// @internal -export function divideInt(a, b) { - return Math.trunc(divideFloat(a, b)); -} - -// @internal -export function divideFloat(a, b) { - if (b === 0) { - return 0; - } else { - return a / b; - } -} - -// @internal -export function makeError(variant, module, line, fn, message, extra) { - let error = new globalThis.Error(message); - error.gleam_error = variant; - error.module = module; - error.line = line; - error.function = fn; - // TODO: Remove this with Gleam v2.0.0 - error.fn = fn; - for (let k in extra) error[k] = extra[k]; - return error; -} diff --git a/test-output/cases/echo_bitarray/build/packages/packages.toml b/test-output/cases/echo_bitarray/build/packages/packages.toml deleted file mode 100644 index e74c18552bb..00000000000 --- a/test-output/cases/echo_bitarray/build/packages/packages.toml +++ /dev/null @@ -1 +0,0 @@ -[packages] diff --git a/test-output/cases/echo_bitarray/manifest.toml b/test-output/cases/echo_bitarray/manifest.toml deleted file mode 100644 index c5d779a3f81..00000000000 --- a/test-output/cases/echo_bitarray/manifest.toml +++ /dev/null @@ -1,7 +0,0 @@ -# This file was generated by Gleam -# You typically do not need to edit this file - -packages = [ -] - -[requirements] diff --git a/test-output/cases/echo_bool/build/dev/erlang/echo_bool/_gleam_artefacts/echo_bool@@main.erl b/test-output/cases/echo_bool/build/dev/erlang/echo_bool/_gleam_artefacts/echo_bool@@main.erl deleted file mode 100644 index 59a76159133..00000000000 --- a/test-output/cases/echo_bool/build/dev/erlang/echo_bool/_gleam_artefacts/echo_bool@@main.erl +++ /dev/null @@ -1,99 +0,0 @@ --module('echo_bool@@main'). --export([run/1]). - --define(red, "\e[31;1m"). --define(grey, "\e[90m"). --define(reset_color, "\e[39m"). --define(reset_all, "\e[0m"). - -run(Module) -> - io:setopts(standard_io, [binary, {encoding, utf8}]), - io:setopts(standard_error, [{encoding, utf8}]), - process_flag(trap_exit, true), - Pid = spawn_link(fun() -> run_module(Module) end), - receive - {'EXIT', Pid, {Reason, StackTrace}} -> - print_error(exit, Reason, StackTrace), - init:stop(1) - end. - -run_module(Module) -> - try - {ok, _} = application:ensure_all_started('echo_bool'), - erlang:process_flag(trap_exit, false), - Module:main(), - erlang:halt(0) - catch - Class:Reason:StackTrace -> - print_error(Class, Reason, StackTrace), - init:stop(1) - end. - -print_error(Class, Error, Stacktrace) -> - Printed = [ - ?red, "runtime error", ?reset_color, ": ", error_class(Class, Error), ?reset_all, - "\n\n", - error_message(Error), - "\n\n", - error_details(Class, Error), - "stacktrace:\n", - [error_frame(Line) || Line <- refine_first(Error, Stacktrace)] - ], - io:format(standard_error, "~ts~n", [Printed]). - -refine_first(#{gleam_error := _, line := L}, [{M, F, A, [{file, Fi} | _]} | S]) -> - [{M, F, A, [{file, Fi}, {line, L}]} | S]; -refine_first(_, S) -> - S. - -error_class(_, #{gleam_error := panic}) -> "panic"; -error_class(_, #{gleam_error := todo}) -> "todo"; -error_class(_, #{gleam_error := let_assert}) -> "let assert"; -error_class(Class, _) -> ["Erlang ", atom_to_binary(Class)]. - -error_message(#{gleam_error := _, message := M}) -> - M; -error_message(undef) -> - <<"A function was called but it did not exist."/utf8 >>; -error_message({case_clause, _}) -> - <<"No pattern matched in an Erlang case expression."/utf8>>; -error_message({badmatch, _}) -> - <<"An Erlang assignment pattern did not match."/utf8>>; -error_message(function_clause) -> - <<"No Erlang function clause matched the arguments it was called with."/utf8>>; -error_message(_) -> - <<"An error occurred outside of Gleam."/utf8>>. - -error_details(_, #{gleam_error := let_assert, value := V}) -> - ["unmatched value:\n ", print_term(V), $\n, $\n]; -error_details(_, {case_clause, V}) -> - ["unmatched value:\n ", print_term(V), $\n, $\n]; -error_details(_, {badmatch, V}) -> - ["unmatched value:\n ", print_term(V), $\n, $\n]; -error_details(_, #{gleam_error := _}) -> - []; -error_details(error, function_clause) -> - []; -error_details(error, undef) -> - []; -error_details(C, E) -> - ["erlang:", atom_to_binary(C), $(, print_term(E), $), $\n, $\n]. - -print_term(T) -> - try - gleam@string:inspect(T) - catch - _:_ -> io_lib:format("~p", [T]) - end. - -error_frame({?MODULE, _, _, _}) -> []; -error_frame({erl_eval, _, _, _}) -> []; -error_frame({init, _, _, _}) -> []; -error_frame({M, F, _, O}) -> - M1 = string:replace(atom_to_binary(M), "@", "/", all), - [" ", M1, $., atom_to_binary(F), error_frame_end(O), $\n]. - -error_frame_end([{file, Fi}, {line, L} | _]) -> - [?grey, $\s, Fi, $:, integer_to_binary(L), ?reset_all]; -error_frame_end(_) -> - [?grey, " unknown source", ?reset_all]. \ No newline at end of file diff --git a/test-output/cases/echo_bool/build/dev/erlang/echo_bool/_gleam_artefacts/gleam@@compile.erl b/test-output/cases/echo_bool/build/dev/erlang/echo_bool/_gleam_artefacts/gleam@@compile.erl deleted file mode 100644 index 3e0a645b737..00000000000 --- a/test-output/cases/echo_bool/build/dev/erlang/echo_bool/_gleam_artefacts/gleam@@compile.erl +++ /dev/null @@ -1,163 +0,0 @@ -#!/usr/bin/env escript --mode(compile). - -% TODO: Don't concurrently print warnings and errors -% TODO: Some tests - -main(_) -> compile_package_loop(). - -compile_package_loop() -> - case file:read_line(standard_io) of - eof -> ok; - {ok, Line} -> - Chars = unicode:characters_to_list(Line), - {ok, Tokens, _} = erl_scan:string(Chars), - {ok, {Lib, Out, Modules}} = erl_parse:parse_term(Tokens), - case compile_package(Lib, Out, Modules) of - ok -> io:put_chars("gleam-compile-result-ok\n"); - err -> io:put_chars("gleam-compile-result-error\n") - end, - compile_package_loop() - end. - -compile_package(Lib, Out, Modules) -> - IsElixirModule = fun(Module) -> - filename:extension(Module) =:= ".ex" - end, - {ElixirModules, ErlangModules} = lists:partition(IsElixirModule, Modules), - ok = configure_logging(), - ok = add_lib_to_erlang_path(Lib), - ok = filelib:ensure_dir([Out, $/]), - {ErlangOk, _ErlangBeams} = compile_erlang(ErlangModules, Out), - {ElixirOk, _ElixirBeams} = case ErlangOk of - true -> compile_elixir(ElixirModules, Out); - false -> {false, []} - end, - ok = del_lib_from_erlang_path(Lib), - case ErlangOk and ElixirOk of - true -> ok; - false -> err - end. - -compile_erlang(Modules, Out) -> - Workers = start_compiler_workers(Out), - ok = producer_loop(Modules, Workers), - collect_results({true, []}). - -collect_results(Acc = {Result, Beams}) -> - receive - {compiled, Beam} -> collect_results({Result, [Beam | Beams]}); - failed -> collect_results({false, Beams}) - after 0 -> Acc - end. - -producer_loop([], 0) -> - ok; -producer_loop([], Workers) -> - receive - {work_please, _} -> producer_loop([], Workers - 1) - end; -producer_loop([Module | Modules], Workers) -> - receive - {work_please, Worker} -> - erlang:send(Worker, {module, Module}), - producer_loop(Modules, Workers) - end. - -start_compiler_workers(Out) -> - Parent = self(), - NumSchedulers = erlang:system_info(schedulers), - SpawnWorker = fun(_) -> - erlang:spawn_link(fun() -> worker_loop(Parent, Out) end) - end, - lists:foreach(SpawnWorker, lists:seq(1, NumSchedulers)), - NumSchedulers. - -worker_loop(Parent, Out) -> - Options = [report_errors, report_warnings, debug_info, {outdir, Out}], - erlang:send(Parent, {work_please, self()}), - receive - {module, Module} -> - log({compiling, Module}), - case compile:file(Module, Options) of - {ok, ModuleName} -> - Beam = filename:join(Out, ModuleName) ++ ".beam", - Message = {compiled, Beam}, - log(Message), - erlang:send(Parent, Message); - error -> - log({failed, Module}), - erlang:send(Parent, failed) - end, - worker_loop(Parent, Out) - end. - -compile_elixir(Modules, Out) -> - Error = [ - "The program elixir was not found. Is it installed?", - $\n, - "Documentation for installing Elixir can be viewed here:", - $\n, - "https://elixir-lang.org/install.html" - ], - case Modules of - [] -> {true, []}; - _ -> - log({starting, "compiler.app"}), - ok = application:start(compiler), - log({starting, "elixir.app"}), - case application:start(elixir) of - ok -> do_compile_elixir(Modules, Out); - _ -> - io:put_chars(standard_error, [Error, $\n]), - {false, []} - end - end. - -do_compile_elixir(Modules, Out) -> - ModuleBins = lists:map(fun(Module) -> - log({compiling, Module}), - list_to_binary(Module) - end, Modules), - OutBin = list_to_binary(Out), - Options = [{dest, OutBin}], - % Silence "redefining module" warnings. - % Compiled modules in the build directory are added to the code path. - % These warnings result from recompiling loaded modules. - % TODO: This line can likely be removed if/when the build directory is cleaned before every compilation. - 'Elixir.Code':compiler_options([{ignore_module_conflict, true}]), - case 'Elixir.Kernel.ParallelCompiler':compile_to_path(ModuleBins, OutBin, Options) of - {ok, ModuleAtoms, _} -> - ToBeam = fun(ModuleAtom) -> - Beam = filename:join(Out, atom_to_list(ModuleAtom)) ++ ".beam", - log({compiled, Beam}), - Beam - end, - {true, lists:map(ToBeam, ModuleAtoms)}; - {error, Errors, _} -> - % Log all filenames associated with modules that failed to compile. - % Note: The compiler prints compilation errors upon encountering them. - ErrorFiles = lists:usort([File || {File, _, _} <- Errors]), - Log = fun(File) -> - log({failed, binary_to_list(File)}) - end, - lists:foreach(Log, ErrorFiles), - {false, []}; - _ -> {false, []} - end. - -add_lib_to_erlang_path(Lib) -> - code:add_paths(filelib:wildcard([Lib, "/*/ebin"])). - -del_lib_from_erlang_path(Lib) -> - code:del_paths(filelib:wildcard([Lib, "/*/ebin"])). - -configure_logging() -> - Enabled = os:getenv("GLEAM_LOG") /= false, - persistent_term:put(gleam_logging_enabled, Enabled). - -log(Term) -> - case persistent_term:get(gleam_logging_enabled) of - true -> erlang:display(Term), ok; - false -> ok - end. diff --git a/test-output/cases/echo_bool/build/dev/erlang/echo_bool/_gleam_artefacts/main.cache b/test-output/cases/echo_bool/build/dev/erlang/echo_bool/_gleam_artefacts/main.cache deleted file mode 100644 index 5c77a489afe..00000000000 Binary files a/test-output/cases/echo_bool/build/dev/erlang/echo_bool/_gleam_artefacts/main.cache and /dev/null differ diff --git a/test-output/cases/echo_bool/build/dev/erlang/echo_bool/_gleam_artefacts/main.cache_meta b/test-output/cases/echo_bool/build/dev/erlang/echo_bool/_gleam_artefacts/main.cache_meta deleted file mode 100644 index 0c91c21bd01..00000000000 Binary files a/test-output/cases/echo_bool/build/dev/erlang/echo_bool/_gleam_artefacts/main.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_bool/build/dev/erlang/echo_bool/_gleam_artefacts/main.cache_warnings b/test-output/cases/echo_bool/build/dev/erlang/echo_bool/_gleam_artefacts/main.cache_warnings deleted file mode 100644 index 1b1cb4d44c5..00000000000 Binary files a/test-output/cases/echo_bool/build/dev/erlang/echo_bool/_gleam_artefacts/main.cache_warnings and /dev/null differ diff --git a/test-output/cases/echo_bool/build/dev/erlang/echo_bool/_gleam_artefacts/main.erl b/test-output/cases/echo_bool/build/dev/erlang/echo_bool/_gleam_artefacts/main.erl deleted file mode 100644 index 6f81e258b89..00000000000 --- a/test-output/cases/echo_bool/build/dev/erlang/echo_bool/_gleam_artefacts/main.erl +++ /dev/null @@ -1,190 +0,0 @@ --module(main). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([main/0]). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_bool/src/main.gleam", 1). --spec main() -> boolean(). -main() -> - echo(true, "src/main.gleam", 2), - echo(false, "src/main.gleam", 3). - --define(is_lowercase_char(X), (X > 96 andalso X < 123)). --define(is_underscore_char(X), (X == 95)). --define(is_digit_char(X), (X > 47 andalso X < 58)). --define(could_be_record(Tuple), - erlang:is_tuple(Tuple) andalso - erlang:is_atom(erlang:element(1, Tuple)) andalso - erlang:element(1, Tuple) =/= false andalso - erlang:element(1, Tuple) =/= true andalso - erlang:element(1, Tuple) =/= nil -). --define(is_atom_char(C), - (?is_lowercase_char(C) orelse - ?is_underscore_char(C) orelse - ?is_digit_char(C)) -). - --define(grey, "\e[90m"). --define(reset_color, "\e[39m"). - -echo(Value, File, Line) -> - StringLine = erlang:integer_to_list(Line), - StringValue = echo@inspect(Value), - io:put_chars( - standard_error, - [?grey, File, $:, StringLine, ?reset_color, $\n, StringValue, $\n] - ), - Value. - -echo@inspect(Value) -> - case Value of - nil -> "Nil"; - true -> "True"; - false -> "False"; - Int when erlang:is_integer(Int) -> erlang:integer_to_list(Int); - Float when erlang:is_float(Float) -> io_lib_format:fwrite_g(Float); - Binary when erlang:is_binary(Binary) -> inspect@binary(Binary); - Bits when erlang:is_bitstring(Bits) -> inspect@bit_array(Bits); - Atom when erlang:is_atom(Atom) -> inspect@atom(Atom); - List when erlang:is_list(List) -> inspect@list(List); - Map when erlang:is_map(Map) -> inspect@map(Map); - Record when ?could_be_record(Record) -> inspect@record(Record); - Tuple when erlang:is_tuple(Tuple) -> inspect@tuple(Tuple); - Function when erlang:is_function(Function) -> inspect@function(Function); - Any -> ["//erl(", io_lib:format("~p", [Any]), ")"] - end. - -inspect@bit_array(Bits) -> - Pieces = inspect@bit_array_pieces(Bits, []), - Inner = lists:join(", ", lists:reverse(Pieces)), - ["<<", Inner, ">>"]. - -inspect@bit_array_pieces(Bits, Acc) -> - case Bits of - <<>> -> - Acc; - <> -> - inspect@bit_array_pieces(Rest, [erlang:integer_to_binary(Byte) | Acc]); - _ -> - Size = erlang:bit_size(Bits), - <> = Bits, - SizeString = [":size(", erlang:integer_to_binary(Size), ")"], - Piece = [erlang:integer_to_binary(RemainingBits), SizeString], - [Piece | Acc] - end. - -inspect@binary(Binary) -> - case inspect@maybe_utf8_string(Binary, <<>>) of - {ok, InspectedUtf8String} -> - InspectedUtf8String; - {error, not_a_utf8_string} -> - Segments = [erlang:integer_to_list(X) || <> <= Binary], - ["<<", lists:join(", ", Segments), ">>"] - end. - -inspect@atom(Atom) -> - Binary = erlang:atom_to_binary(Atom), - case inspect@maybe_gleam_atom(Binary, none, <<>>) of - {ok, Inspected} -> Inspected; - {error, _} -> ["atom.create_from_string(\"", Binary, "\")"] - end. - -inspect@list(List) -> - case inspect@proper_or_improper_list(List) of - {proper, Elements} -> ["[", Elements, "]"]; - {improper, Elements} -> ["//erl([", Elements, "])"] - end. - -inspect@map(Map) -> - Fields = [ - [<<"#(">>, echo@inspect(Key), <<", ">>, echo@inspect(Value), <<")">>] - || {Key, Value} <- maps:to_list(Map) - ], - ["dict.from_list([", lists:join(", ", Fields), "])"]. - -inspect@record(Record) -> - [Atom | ArgsList] = erlang:tuple_to_list(Record), - Args = lists:join(", ", lists:map(fun echo@inspect/1, ArgsList)), - [echo@inspect(Atom), "(", Args, ")"]. - -inspect@tuple(Tuple) -> - Elements = lists:map(fun echo@inspect/1, erlang:tuple_to_list(Tuple)), - ["#(", lists:join(", ", Elements), ")"]. - -inspect@function(Function) -> - {arity, Arity} = erlang:fun_info(Function, arity), - ArgsAsciiCodes = lists:seq($a, $a + Arity - 1), - Args = lists:join(", ", lists:map(fun(Arg) -> <> end, ArgsAsciiCodes)), - ["//fn(", Args, ") { ... }"]. - -inspect@maybe_utf8_string(Binary, Acc) -> - case Binary of - <<>> -> - {ok, <<$", Acc/binary, $">>}; - <> -> - Escaped = inspect@escape_grapheme(First), - inspect@maybe_utf8_string(Rest, <>); - _ -> - {error, not_a_utf8_string} - end. - -inspect@escape_grapheme(Char) -> - case Char of - $" -> <<$\\, $">>; - $\\ -> <<$\\, $\\>>; - $\r -> <<$\\, $r>>; - $\n -> <<$\\, $n>>; - $\t -> <<$\\, $t>>; - $\f -> <<$\\, $f>>; - X when X > 126, X < 160 -> inspect@convert_to_u(X); - X when X < 32 -> inspect@convert_to_u(X); - Other -> <> - end. - -inspect@convert_to_u(Code) -> - erlang:list_to_binary(io_lib:format("\\u{~4.16.0B}", [Code])). - -inspect@proper_or_improper_list(List) -> - case List of - [] -> - {proper, []}; - [First] -> - {proper, [echo@inspect(First)]}; - [First | Rest] when erlang:is_list(Rest) -> - {Kind, Inspected} = inspect@proper_or_improper_list(Rest), - {Kind, [echo@inspect(First), ", " | Inspected]}; - [First | ImproperRest] -> - {improper, [echo@inspect(First), " | ", echo@inspect(ImproperRest)]} - end. - -inspect@maybe_gleam_atom(Atom, PrevChar, Acc) -> - case {Atom, PrevChar} of - {<<>>, none} -> - {error, nil}; - {<>, none} when ?is_digit_char(First) -> - {error, nil}; - {<<"_", _/binary>>, none} -> - {error, nil}; - {<<"_">>, _} -> - {error, nil}; - {<<"_", _/binary>>, $_} -> - {error, nil}; - {<>, _} when not ?is_atom_char(First) -> - {error, nil}; - {<>, none} -> - inspect@maybe_gleam_atom(Rest, First, <>); - {<<"_", Rest/binary>>, _} -> - inspect@maybe_gleam_atom(Rest, $_, Acc); - {<>, $_} -> - inspect@maybe_gleam_atom(Rest, First, <>); - {<>, _} -> - inspect@maybe_gleam_atom(Rest, First, <>); - {<<>>, _} -> - {ok, Acc}; - _ -> - erlang:throw({gleam_error, echo, Atom, PrevChar, Acc}) - end. - -inspect@uppercase(X) -> X - 32. - diff --git a/test-output/cases/echo_bool/build/dev/erlang/echo_bool/ebin/echo_bool.app b/test-output/cases/echo_bool/build/dev/erlang/echo_bool/ebin/echo_bool.app deleted file mode 100644 index 4e995bbd7d8..00000000000 --- a/test-output/cases/echo_bool/build/dev/erlang/echo_bool/ebin/echo_bool.app +++ /dev/null @@ -1,7 +0,0 @@ -{application, echo_bool, [ - {vsn, "1.0.0"}, - {applications, []}, - {description, ""}, - {modules, [main]}, - {registered, []} -]}. diff --git a/test-output/cases/echo_bool/build/dev/erlang/gleam_version b/test-output/cases/echo_bool/build/dev/erlang/gleam_version deleted file mode 100644 index 3e1ad720b13..00000000000 --- a/test-output/cases/echo_bool/build/dev/erlang/gleam_version +++ /dev/null @@ -1 +0,0 @@ -1.5.0 \ No newline at end of file diff --git a/test-output/cases/echo_bool/build/dev/javascript/echo_bool/_gleam_artefacts/main.cache b/test-output/cases/echo_bool/build/dev/javascript/echo_bool/_gleam_artefacts/main.cache deleted file mode 100644 index 5c77a489afe..00000000000 Binary files a/test-output/cases/echo_bool/build/dev/javascript/echo_bool/_gleam_artefacts/main.cache and /dev/null differ diff --git a/test-output/cases/echo_bool/build/dev/javascript/echo_bool/_gleam_artefacts/main.cache_meta b/test-output/cases/echo_bool/build/dev/javascript/echo_bool/_gleam_artefacts/main.cache_meta deleted file mode 100644 index 0c91c21bd01..00000000000 Binary files a/test-output/cases/echo_bool/build/dev/javascript/echo_bool/_gleam_artefacts/main.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_bool/build/dev/javascript/echo_bool/_gleam_artefacts/main.cache_warnings b/test-output/cases/echo_bool/build/dev/javascript/echo_bool/_gleam_artefacts/main.cache_warnings deleted file mode 100644 index 1b1cb4d44c5..00000000000 Binary files a/test-output/cases/echo_bool/build/dev/javascript/echo_bool/_gleam_artefacts/main.cache_warnings and /dev/null differ diff --git a/test-output/cases/echo_bool/build/dev/javascript/echo_bool/gleam.main.mjs b/test-output/cases/echo_bool/build/dev/javascript/echo_bool/gleam.main.mjs deleted file mode 100644 index e230911e646..00000000000 --- a/test-output/cases/echo_bool/build/dev/javascript/echo_bool/gleam.main.mjs +++ /dev/null @@ -1,2 +0,0 @@ -import { main } from "./main.mjs"; -main(); diff --git a/test-output/cases/echo_bool/build/dev/javascript/echo_bool/gleam.mjs b/test-output/cases/echo_bool/build/dev/javascript/echo_bool/gleam.mjs deleted file mode 100644 index 197cbbc35d4..00000000000 --- a/test-output/cases/echo_bool/build/dev/javascript/echo_bool/gleam.mjs +++ /dev/null @@ -1 +0,0 @@ -export * from "../prelude.mjs"; diff --git a/test-output/cases/echo_bool/build/dev/javascript/echo_bool/main.mjs b/test-output/cases/echo_bool/build/dev/javascript/echo_bool/main.mjs deleted file mode 100644 index 5668ff9f48c..00000000000 --- a/test-output/cases/echo_bool/build/dev/javascript/echo_bool/main.mjs +++ /dev/null @@ -1,128 +0,0 @@ -import { - BitArray as $BitArray, - List as $List, - UtfCodepoint as $UtfCodepoint, - CustomType as $CustomType, -} from "./gleam.mjs"; - -export function main() { - echo(true, "src/main.gleam", 2); - return echo(false, "src/main.gleam", 3); -} - -function echo(value, file, line) { - const grey = "\u001b[90m"; - const reset_color = "\u001b[39m"; - const file_line = `${file}:${line}`; - const string_value = echo$inspect(value); - - if (typeof process === "object" && process.stderr?.write) { - // If we're in Node.js, use `stderr` - const string = `${grey}${file_line}${reset_color}\n${string_value}\n`; - process.stderr.write(string); - } else if (typeof Deno === "object") { - // If we're in Deno, use `stderr` - const string = `${grey}${file_line}${reset_color}\n${string_value}\n`; - Deno.stderr.writeSync(new TextEncoder().encode(string)); - } else { - // Otherwise, use `console.log` - // The browser's console.log doesn't support ansi escape codes - const string = `${file_line}\n${string_value}`; - console.log(string); - } - - return value; -} - -function echo$inspectString(str) { - let new_str = '"'; - for (let i = 0; i < str.length; i++) { - let char = str[i]; - if (char == "\n") new_str += "\\n"; - else if (char == "\r") new_str += "\\r"; - else if (char == "\t") new_str += "\\t"; - else if (char == "\f") new_str += "\\f"; - else if (char == "\\") new_str += "\\\\"; - else if (char == '"') new_str += '\\"'; - else if (char < " " || (char > "~" && char < "\u{00A0}")) { - new_str += "\\u{" + char.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0") + "}"; - } else { - new_str += char; - } - } - new_str += '"'; - return new_str; -} - -function echo$inspectDict(map) { - let body = "dict.from_list(["; - let first = true; - map.forEach((value, key) => { - if (!first) body = body + ", "; - body = body + "#(" + echo$inspect(key) + ", " + echo$inspect(value) + ")"; - first = false; - }); - return body + "])"; -} - -function echo$inspectCustomType(record) { - const props = Object.keys(record) - .map((label) => { - const value = echo$inspect(record[label]); - return isNaN(parseInt(label)) ? `${label}: ${value}` : value; - }) - .join(", "); - return props ? `${record.constructor.name}(${props})` : record.constructor.name; -} - -function echo$inspectObject(v) { - const name = Object.getPrototypeOf(v)?.constructor?.name || "Object"; - const props = []; - for (const k of Object.keys(v)) { - props.push(`${echo$inspect(k)}: ${echo$inspect(v[k])}`); - } - const body = props.length ? " " + props.join(", ") + " " : ""; - const head = name === "Object" ? "" : name + " "; - return `//js(${head}{${body}})`; -} - -function echo$inspect(v) { - const t = typeof v; - if (v === true) return "True"; - if (v === false) return "False"; - if (v === null) return "//js(null)"; - if (v === undefined) return "Nil"; - if (t === "string") return echo$inspectString(v); - if (t === "bigint" || t === "number") return v.toString(); - if (Array.isArray(v)) return `#(${v.map(echo$inspect).join(", ")})`; - if (v instanceof $List) return `[${v.toArray().map(echo$inspect).join(", ")}]`; - if (v instanceof $UtfCodepoint) return `//utfcodepoint(${String.fromCodePoint(v.value)})`; - if (v instanceof $BitArray) return `<<${Array.from(v.buffer).join(", ")}>>`; - if (v instanceof $CustomType) return echo$inspectCustomType(v); - if (echo$isDict(v)) return echo$inspectDict(v); - if (v instanceof Set) return `//js(Set(${[...v].map(echo$inspect).join(", ")}))`; - if (v instanceof RegExp) return `//js(${v})`; - if (v instanceof Date) return `//js(Date("${v.toISOString()}"))`; - if (v instanceof Function) { - const args = []; - for (const i of Array(v.length).keys()) args.push(String.fromCharCode(i + 97)); - return `//fn(${args.join(", ")}) { ... }`; - } - return echo$inspectObject(v); -} - -function echo$isDict(value) { - try { - // We can only check if an object is a stdlib Dict if it is one of the - // project's dependencies. - // The `Dict` class is the default export of `stdlib/dict.mjs` - // that we import as `$stdlib$dict`. - return value instanceof $stdlib$dict.default; - } catch { - // If stdlib is not one of the project's dependencies then `$stdlib$dict` - // will not have been imported and the check will throw an exception meaning - // we can't check if something is actually a `Dict`. - return false; - } -} - diff --git a/test-output/cases/echo_bool/build/dev/javascript/gleam_version b/test-output/cases/echo_bool/build/dev/javascript/gleam_version deleted file mode 100644 index 3e1ad720b13..00000000000 --- a/test-output/cases/echo_bool/build/dev/javascript/gleam_version +++ /dev/null @@ -1 +0,0 @@ -1.5.0 \ No newline at end of file diff --git a/test-output/cases/echo_bool/build/dev/javascript/prelude.mjs b/test-output/cases/echo_bool/build/dev/javascript/prelude.mjs deleted file mode 100644 index d2adeef273f..00000000000 --- a/test-output/cases/echo_bool/build/dev/javascript/prelude.mjs +++ /dev/null @@ -1,455 +0,0 @@ -// Values marked with @internal are not part of the public API and may change -// without notice. - -export class CustomType { - withFields(fields) { - let properties = Object.keys(this).map((label) => - label in fields ? fields[label] : this[label], - ); - return new this.constructor(...properties); - } -} - -export class List { - static fromArray(array, tail) { - let t = tail || new Empty(); - for (let i = array.length - 1; i >= 0; --i) { - t = new NonEmpty(array[i], t); - } - return t; - } - - [Symbol.iterator]() { - return new ListIterator(this); - } - - toArray() { - return [...this]; - } - - // @internal - atLeastLength(desired) { - for (let _ of this) { - if (desired <= 0) return true; - desired--; - } - return desired <= 0; - } - - // @internal - hasLength(desired) { - for (let _ of this) { - if (desired <= 0) return false; - desired--; - } - return desired === 0; - } - - // @internal - countLength() { - let length = 0; - for (let _ of this) length++; - return length; - } -} - -// @internal -export function prepend(element, tail) { - return new NonEmpty(element, tail); -} - -export function toList(elements, tail) { - return List.fromArray(elements, tail); -} - -// @internal -class ListIterator { - #current; - - constructor(current) { - this.#current = current; - } - - next() { - if (this.#current instanceof Empty) { - return { done: true }; - } else { - let { head, tail } = this.#current; - this.#current = tail; - return { value: head, done: false }; - } - } -} - -export class Empty extends List {} - -export class NonEmpty extends List { - constructor(head, tail) { - super(); - this.head = head; - this.tail = tail; - } -} - -export class BitArray { - constructor(buffer) { - if (!(buffer instanceof Uint8Array)) { - throw "BitArray can only be constructed from a Uint8Array"; - } - this.buffer = buffer; - } - - // @internal - get length() { - return this.buffer.length; - } - - // @internal - byteAt(index) { - return this.buffer[index]; - } - - // @internal - floatFromSlice(start, end, isBigEndian) { - return byteArrayToFloat(this.buffer, start, end, isBigEndian); - } - - // @internal - intFromSlice(start, end, isBigEndian, isSigned) { - return byteArrayToInt(this.buffer, start, end, isBigEndian, isSigned); - } - - // @internal - binaryFromSlice(start, end) { - return new BitArray(this.buffer.slice(start, end)); - } - - // @internal - sliceAfter(index) { - return new BitArray(this.buffer.slice(index)); - } -} - -export class UtfCodepoint { - constructor(value) { - this.value = value; - } -} - -// @internal -export function toBitArray(segments) { - if (segments.length === 0) { - return new BitArray(new Uint8Array()); - } - - if (segments.length === 1) { - // When there is a single Uint8Array segment, pass it directly to the bit - // array constructor to avoid a copy - if (segments[0] instanceof Uint8Array) { - return new BitArray(segments[0]); - } - - return new BitArray(new Uint8Array(segments)); - } - - // Count the total number of bytes, and check if there are any Uint8Array - // segments - let bytes = 0; - let hasUint8ArraySegment = false; - for (const segment of segments) { - if (segment instanceof Uint8Array) { - bytes += segment.byteLength; - hasUint8ArraySegment = true; - } else { - bytes++; - } - } - - // If there aren't any Uint8Array segments then pass the segments array - // directly to the Uint8Array constructor - if (!hasUint8ArraySegment) { - return new BitArray(new Uint8Array(segments)); - } - - // Copy the segments into a Uint8Array - let u8Array = new Uint8Array(bytes); - let cursor = 0; - for (let segment of segments) { - if (segment instanceof Uint8Array) { - u8Array.set(segment, cursor); - cursor += segment.byteLength; - } else { - u8Array[cursor] = segment; - cursor++; - } - } - - return new BitArray(u8Array); -} - -// @internal -// Derived from this answer https://stackoverflow.com/questions/8482309/converting-javascript-integer-to-byte-array-and-back -export function sizedInt(value, size, isBigEndian) { - if (size < 0) { - return new Uint8Array(); - } - if (size % 8 != 0) { - const msg = `Bit arrays must be byte aligned on JavaScript, got size of ${size} bits`; - throw new globalThis.Error(msg); - } - - const byteArray = new Uint8Array(size / 8); - - // Convert negative number to two's complement representation - if (value < 0) { - value = 2 ** size + value; - } - - if (isBigEndian) { - for (let i = byteArray.length - 1; i >= 0; i--) { - const byte = value % 256; - byteArray[i] = byte; - value = (value - byte) / 256; - } - } else { - for (let i = 0; i < byteArray.length; i++) { - const byte = value % 256; - byteArray[i] = byte; - value = (value - byte) / 256; - } - } - - return byteArray; -} - -// @internal -export function byteArrayToInt(byteArray, start, end, isBigEndian, isSigned) { - let value = 0; - - // Read bytes as an unsigned integer value - if (isBigEndian) { - for (let i = start; i < end; i++) { - value = value * 256 + byteArray[i]; - } - } else { - for (let i = end - 1; i >= start; i--) { - value = value * 256 + byteArray[i]; - } - } - - if (isSigned) { - const byteSize = end - start; - - const highBit = 2 ** (byteSize * 8 - 1); - - // If the high bit is set and this is a signed integer, reinterpret as - // two's complement - if (value >= highBit) { - value -= highBit * 2; - } - } - - return value; -} - -// @internal -export function byteArrayToFloat(byteArray, start, end, isBigEndian) { - const view = new DataView(byteArray.buffer); - - const byteSize = end - start; - - if (byteSize === 8) { - return view.getFloat64(start, !isBigEndian); - } else if (byteSize === 4) { - return view.getFloat32(start, !isBigEndian); - } else { - const msg = `Sized floats must be 32-bit or 64-bit on JavaScript, got size of ${byteSize * 8} bits`; - throw new globalThis.Error(msg); - } -} - -// @internal -export function stringBits(string) { - return new TextEncoder().encode(string); -} - -// @internal -export function codepointBits(codepoint) { - return stringBits(String.fromCodePoint(codepoint.value)); -} - -// @internal -export function sizedFloat(float, size, isBigEndian) { - if (size !== 32 && size !== 64) { - const msg = `Sized floats must be 32-bit or 64-bit on JavaScript, got size of ${size} bits`; - throw new globalThis.Error(msg); - } - - const byteArray = new Uint8Array(size / 8); - - const view = new DataView(byteArray.buffer); - - if (size == 64) { - view.setFloat64(0, float, !isBigEndian); - } else if (size === 32) { - view.setFloat32(0, float, !isBigEndian); - } - - return byteArray; -} - -export class Result extends CustomType { - // @internal - static isResult(data) { - return data instanceof Result; - } -} - -export class Ok extends Result { - constructor(value) { - super(); - this[0] = value; - } - - // @internal - isOk() { - return true; - } -} - -export class Error extends Result { - constructor(detail) { - super(); - this[0] = detail; - } - - // @internal - isOk() { - return false; - } -} - -export function isEqual(x, y) { - let values = [x, y]; - - while (values.length) { - let a = values.pop(); - let b = values.pop(); - if (a === b) continue; - - if (!isObject(a) || !isObject(b)) return false; - let unequal = - !structurallyCompatibleObjects(a, b) || - unequalDates(a, b) || - unequalBuffers(a, b) || - unequalArrays(a, b) || - unequalMaps(a, b) || - unequalSets(a, b) || - unequalRegExps(a, b); - if (unequal) return false; - - const proto = Object.getPrototypeOf(a); - if (proto !== null && typeof proto.equals === "function") { - try { - if (a.equals(b)) continue; - else return false; - } catch {} - } - - let [keys, get] = getters(a); - for (let k of keys(a)) { - values.push(get(a, k), get(b, k)); - } - } - - return true; -} - -function getters(object) { - if (object instanceof Map) { - return [(x) => x.keys(), (x, y) => x.get(y)]; - } else { - let extra = object instanceof globalThis.Error ? ["message"] : []; - return [(x) => [...extra, ...Object.keys(x)], (x, y) => x[y]]; - } -} - -function unequalDates(a, b) { - return a instanceof Date && (a > b || a < b); -} - -function unequalBuffers(a, b) { - return ( - a.buffer instanceof ArrayBuffer && - a.BYTES_PER_ELEMENT && - !(a.byteLength === b.byteLength && a.every((n, i) => n === b[i])) - ); -} - -function unequalArrays(a, b) { - return Array.isArray(a) && a.length !== b.length; -} - -function unequalMaps(a, b) { - return a instanceof Map && a.size !== b.size; -} - -function unequalSets(a, b) { - return ( - a instanceof Set && (a.size != b.size || [...a].some((e) => !b.has(e))) - ); -} - -function unequalRegExps(a, b) { - return a instanceof RegExp && (a.source !== b.source || a.flags !== b.flags); -} - -function isObject(a) { - return typeof a === "object" && a !== null; -} - -function structurallyCompatibleObjects(a, b) { - if (typeof a !== "object" && typeof b !== "object" && (!a || !b)) - return false; - - let nonstructural = [Promise, WeakSet, WeakMap, Function]; - if (nonstructural.some((c) => a instanceof c)) return false; - - return a.constructor === b.constructor; -} - -// @internal -export function remainderInt(a, b) { - if (b === 0) { - return 0; - } else { - return a % b; - } -} - -// @internal -export function divideInt(a, b) { - return Math.trunc(divideFloat(a, b)); -} - -// @internal -export function divideFloat(a, b) { - if (b === 0) { - return 0; - } else { - return a / b; - } -} - -// @internal -export function makeError(variant, module, line, fn, message, extra) { - let error = new globalThis.Error(message); - error.gleam_error = variant; - error.module = module; - error.line = line; - error.function = fn; - // TODO: Remove this with Gleam v2.0.0 - error.fn = fn; - for (let k in extra) error[k] = extra[k]; - return error; -} diff --git a/test-output/cases/echo_bool/build/packages/packages.toml b/test-output/cases/echo_bool/build/packages/packages.toml deleted file mode 100644 index e74c18552bb..00000000000 --- a/test-output/cases/echo_bool/build/packages/packages.toml +++ /dev/null @@ -1 +0,0 @@ -[packages] diff --git a/test-output/cases/echo_bool/manifest.toml b/test-output/cases/echo_bool/manifest.toml deleted file mode 100644 index c5d779a3f81..00000000000 --- a/test-output/cases/echo_bool/manifest.toml +++ /dev/null @@ -1,7 +0,0 @@ -# This file was generated by Gleam -# You typically do not need to edit this file - -packages = [ -] - -[requirements] diff --git a/test-output/cases/echo_custom_type/build/dev/erlang/echo_custom_type/_gleam_artefacts/echo_custom_type@@main.erl b/test-output/cases/echo_custom_type/build/dev/erlang/echo_custom_type/_gleam_artefacts/echo_custom_type@@main.erl deleted file mode 100644 index 62cb39e944a..00000000000 --- a/test-output/cases/echo_custom_type/build/dev/erlang/echo_custom_type/_gleam_artefacts/echo_custom_type@@main.erl +++ /dev/null @@ -1,99 +0,0 @@ --module('echo_custom_type@@main'). --export([run/1]). - --define(red, "\e[31;1m"). --define(grey, "\e[90m"). --define(reset_color, "\e[39m"). --define(reset_all, "\e[0m"). - -run(Module) -> - io:setopts(standard_io, [binary, {encoding, utf8}]), - io:setopts(standard_error, [{encoding, utf8}]), - process_flag(trap_exit, true), - Pid = spawn_link(fun() -> run_module(Module) end), - receive - {'EXIT', Pid, {Reason, StackTrace}} -> - print_error(exit, Reason, StackTrace), - init:stop(1) - end. - -run_module(Module) -> - try - {ok, _} = application:ensure_all_started('echo_custom_type'), - erlang:process_flag(trap_exit, false), - Module:main(), - erlang:halt(0) - catch - Class:Reason:StackTrace -> - print_error(Class, Reason, StackTrace), - init:stop(1) - end. - -print_error(Class, Error, Stacktrace) -> - Printed = [ - ?red, "runtime error", ?reset_color, ": ", error_class(Class, Error), ?reset_all, - "\n\n", - error_message(Error), - "\n\n", - error_details(Class, Error), - "stacktrace:\n", - [error_frame(Line) || Line <- refine_first(Error, Stacktrace)] - ], - io:format(standard_error, "~ts~n", [Printed]). - -refine_first(#{gleam_error := _, line := L}, [{M, F, A, [{file, Fi} | _]} | S]) -> - [{M, F, A, [{file, Fi}, {line, L}]} | S]; -refine_first(_, S) -> - S. - -error_class(_, #{gleam_error := panic}) -> "panic"; -error_class(_, #{gleam_error := todo}) -> "todo"; -error_class(_, #{gleam_error := let_assert}) -> "let assert"; -error_class(Class, _) -> ["Erlang ", atom_to_binary(Class)]. - -error_message(#{gleam_error := _, message := M}) -> - M; -error_message(undef) -> - <<"A function was called but it did not exist."/utf8 >>; -error_message({case_clause, _}) -> - <<"No pattern matched in an Erlang case expression."/utf8>>; -error_message({badmatch, _}) -> - <<"An Erlang assignment pattern did not match."/utf8>>; -error_message(function_clause) -> - <<"No Erlang function clause matched the arguments it was called with."/utf8>>; -error_message(_) -> - <<"An error occurred outside of Gleam."/utf8>>. - -error_details(_, #{gleam_error := let_assert, value := V}) -> - ["unmatched value:\n ", print_term(V), $\n, $\n]; -error_details(_, {case_clause, V}) -> - ["unmatched value:\n ", print_term(V), $\n, $\n]; -error_details(_, {badmatch, V}) -> - ["unmatched value:\n ", print_term(V), $\n, $\n]; -error_details(_, #{gleam_error := _}) -> - []; -error_details(error, function_clause) -> - []; -error_details(error, undef) -> - []; -error_details(C, E) -> - ["erlang:", atom_to_binary(C), $(, print_term(E), $), $\n, $\n]. - -print_term(T) -> - try - gleam@string:inspect(T) - catch - _:_ -> io_lib:format("~p", [T]) - end. - -error_frame({?MODULE, _, _, _}) -> []; -error_frame({erl_eval, _, _, _}) -> []; -error_frame({init, _, _, _}) -> []; -error_frame({M, F, _, O}) -> - M1 = string:replace(atom_to_binary(M), "@", "/", all), - [" ", M1, $., atom_to_binary(F), error_frame_end(O), $\n]. - -error_frame_end([{file, Fi}, {line, L} | _]) -> - [?grey, $\s, Fi, $:, integer_to_binary(L), ?reset_all]; -error_frame_end(_) -> - [?grey, " unknown source", ?reset_all]. \ No newline at end of file diff --git a/test-output/cases/echo_custom_type/build/dev/erlang/echo_custom_type/_gleam_artefacts/gleam@@compile.erl b/test-output/cases/echo_custom_type/build/dev/erlang/echo_custom_type/_gleam_artefacts/gleam@@compile.erl deleted file mode 100644 index 3e0a645b737..00000000000 --- a/test-output/cases/echo_custom_type/build/dev/erlang/echo_custom_type/_gleam_artefacts/gleam@@compile.erl +++ /dev/null @@ -1,163 +0,0 @@ -#!/usr/bin/env escript --mode(compile). - -% TODO: Don't concurrently print warnings and errors -% TODO: Some tests - -main(_) -> compile_package_loop(). - -compile_package_loop() -> - case file:read_line(standard_io) of - eof -> ok; - {ok, Line} -> - Chars = unicode:characters_to_list(Line), - {ok, Tokens, _} = erl_scan:string(Chars), - {ok, {Lib, Out, Modules}} = erl_parse:parse_term(Tokens), - case compile_package(Lib, Out, Modules) of - ok -> io:put_chars("gleam-compile-result-ok\n"); - err -> io:put_chars("gleam-compile-result-error\n") - end, - compile_package_loop() - end. - -compile_package(Lib, Out, Modules) -> - IsElixirModule = fun(Module) -> - filename:extension(Module) =:= ".ex" - end, - {ElixirModules, ErlangModules} = lists:partition(IsElixirModule, Modules), - ok = configure_logging(), - ok = add_lib_to_erlang_path(Lib), - ok = filelib:ensure_dir([Out, $/]), - {ErlangOk, _ErlangBeams} = compile_erlang(ErlangModules, Out), - {ElixirOk, _ElixirBeams} = case ErlangOk of - true -> compile_elixir(ElixirModules, Out); - false -> {false, []} - end, - ok = del_lib_from_erlang_path(Lib), - case ErlangOk and ElixirOk of - true -> ok; - false -> err - end. - -compile_erlang(Modules, Out) -> - Workers = start_compiler_workers(Out), - ok = producer_loop(Modules, Workers), - collect_results({true, []}). - -collect_results(Acc = {Result, Beams}) -> - receive - {compiled, Beam} -> collect_results({Result, [Beam | Beams]}); - failed -> collect_results({false, Beams}) - after 0 -> Acc - end. - -producer_loop([], 0) -> - ok; -producer_loop([], Workers) -> - receive - {work_please, _} -> producer_loop([], Workers - 1) - end; -producer_loop([Module | Modules], Workers) -> - receive - {work_please, Worker} -> - erlang:send(Worker, {module, Module}), - producer_loop(Modules, Workers) - end. - -start_compiler_workers(Out) -> - Parent = self(), - NumSchedulers = erlang:system_info(schedulers), - SpawnWorker = fun(_) -> - erlang:spawn_link(fun() -> worker_loop(Parent, Out) end) - end, - lists:foreach(SpawnWorker, lists:seq(1, NumSchedulers)), - NumSchedulers. - -worker_loop(Parent, Out) -> - Options = [report_errors, report_warnings, debug_info, {outdir, Out}], - erlang:send(Parent, {work_please, self()}), - receive - {module, Module} -> - log({compiling, Module}), - case compile:file(Module, Options) of - {ok, ModuleName} -> - Beam = filename:join(Out, ModuleName) ++ ".beam", - Message = {compiled, Beam}, - log(Message), - erlang:send(Parent, Message); - error -> - log({failed, Module}), - erlang:send(Parent, failed) - end, - worker_loop(Parent, Out) - end. - -compile_elixir(Modules, Out) -> - Error = [ - "The program elixir was not found. Is it installed?", - $\n, - "Documentation for installing Elixir can be viewed here:", - $\n, - "https://elixir-lang.org/install.html" - ], - case Modules of - [] -> {true, []}; - _ -> - log({starting, "compiler.app"}), - ok = application:start(compiler), - log({starting, "elixir.app"}), - case application:start(elixir) of - ok -> do_compile_elixir(Modules, Out); - _ -> - io:put_chars(standard_error, [Error, $\n]), - {false, []} - end - end. - -do_compile_elixir(Modules, Out) -> - ModuleBins = lists:map(fun(Module) -> - log({compiling, Module}), - list_to_binary(Module) - end, Modules), - OutBin = list_to_binary(Out), - Options = [{dest, OutBin}], - % Silence "redefining module" warnings. - % Compiled modules in the build directory are added to the code path. - % These warnings result from recompiling loaded modules. - % TODO: This line can likely be removed if/when the build directory is cleaned before every compilation. - 'Elixir.Code':compiler_options([{ignore_module_conflict, true}]), - case 'Elixir.Kernel.ParallelCompiler':compile_to_path(ModuleBins, OutBin, Options) of - {ok, ModuleAtoms, _} -> - ToBeam = fun(ModuleAtom) -> - Beam = filename:join(Out, atom_to_list(ModuleAtom)) ++ ".beam", - log({compiled, Beam}), - Beam - end, - {true, lists:map(ToBeam, ModuleAtoms)}; - {error, Errors, _} -> - % Log all filenames associated with modules that failed to compile. - % Note: The compiler prints compilation errors upon encountering them. - ErrorFiles = lists:usort([File || {File, _, _} <- Errors]), - Log = fun(File) -> - log({failed, binary_to_list(File)}) - end, - lists:foreach(Log, ErrorFiles), - {false, []}; - _ -> {false, []} - end. - -add_lib_to_erlang_path(Lib) -> - code:add_paths(filelib:wildcard([Lib, "/*/ebin"])). - -del_lib_from_erlang_path(Lib) -> - code:del_paths(filelib:wildcard([Lib, "/*/ebin"])). - -configure_logging() -> - Enabled = os:getenv("GLEAM_LOG") /= false, - persistent_term:put(gleam_logging_enabled, Enabled). - -log(Term) -> - case persistent_term:get(gleam_logging_enabled) of - true -> erlang:display(Term), ok; - false -> ok - end. diff --git a/test-output/cases/echo_custom_type/build/dev/erlang/echo_custom_type/_gleam_artefacts/main.cache b/test-output/cases/echo_custom_type/build/dev/erlang/echo_custom_type/_gleam_artefacts/main.cache deleted file mode 100644 index 560b1d4f2c7..00000000000 Binary files a/test-output/cases/echo_custom_type/build/dev/erlang/echo_custom_type/_gleam_artefacts/main.cache and /dev/null differ diff --git a/test-output/cases/echo_custom_type/build/dev/erlang/echo_custom_type/_gleam_artefacts/main.cache_meta b/test-output/cases/echo_custom_type/build/dev/erlang/echo_custom_type/_gleam_artefacts/main.cache_meta deleted file mode 100644 index 9587e761d0a..00000000000 Binary files a/test-output/cases/echo_custom_type/build/dev/erlang/echo_custom_type/_gleam_artefacts/main.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_custom_type/build/dev/erlang/echo_custom_type/_gleam_artefacts/main.cache_warnings b/test-output/cases/echo_custom_type/build/dev/erlang/echo_custom_type/_gleam_artefacts/main.cache_warnings deleted file mode 100644 index 1b1cb4d44c5..00000000000 Binary files a/test-output/cases/echo_custom_type/build/dev/erlang/echo_custom_type/_gleam_artefacts/main.cache_warnings and /dev/null differ diff --git a/test-output/cases/echo_custom_type/build/dev/erlang/echo_custom_type/_gleam_artefacts/main.erl b/test-output/cases/echo_custom_type/build/dev/erlang/echo_custom_type/_gleam_artefacts/main.erl deleted file mode 100644 index f3ee6147d6d..00000000000 --- a/test-output/cases/echo_custom_type/build/dev/erlang/echo_custom_type/_gleam_artefacts/main.erl +++ /dev/null @@ -1,194 +0,0 @@ --module(main). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([main/0]). --export_type([wibble/0]). - --type wibble() :: {wibble, integer(), binary()} | {wobble, list(float())} | woo. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_custom_type/src/main.gleam", 7). --spec main() -> wibble(). -main() -> - echo({wibble, 1, <<"hello"/utf8>>}, "src/main.gleam", 8), - echo({wobble, [1.0, 1.1]}, "src/main.gleam", 9), - echo(woo, "src/main.gleam", 10). - --define(is_lowercase_char(X), (X > 96 andalso X < 123)). --define(is_underscore_char(X), (X == 95)). --define(is_digit_char(X), (X > 47 andalso X < 58)). --define(could_be_record(Tuple), - erlang:is_tuple(Tuple) andalso - erlang:is_atom(erlang:element(1, Tuple)) andalso - erlang:element(1, Tuple) =/= false andalso - erlang:element(1, Tuple) =/= true andalso - erlang:element(1, Tuple) =/= nil -). --define(is_atom_char(C), - (?is_lowercase_char(C) orelse - ?is_underscore_char(C) orelse - ?is_digit_char(C)) -). - --define(grey, "\e[90m"). --define(reset_color, "\e[39m"). - -echo(Value, File, Line) -> - StringLine = erlang:integer_to_list(Line), - StringValue = echo@inspect(Value), - io:put_chars( - standard_error, - [?grey, File, $:, StringLine, ?reset_color, $\n, StringValue, $\n] - ), - Value. - -echo@inspect(Value) -> - case Value of - nil -> "Nil"; - true -> "True"; - false -> "False"; - Int when erlang:is_integer(Int) -> erlang:integer_to_list(Int); - Float when erlang:is_float(Float) -> io_lib_format:fwrite_g(Float); - Binary when erlang:is_binary(Binary) -> inspect@binary(Binary); - Bits when erlang:is_bitstring(Bits) -> inspect@bit_array(Bits); - Atom when erlang:is_atom(Atom) -> inspect@atom(Atom); - List when erlang:is_list(List) -> inspect@list(List); - Map when erlang:is_map(Map) -> inspect@map(Map); - Record when ?could_be_record(Record) -> inspect@record(Record); - Tuple when erlang:is_tuple(Tuple) -> inspect@tuple(Tuple); - Function when erlang:is_function(Function) -> inspect@function(Function); - Any -> ["//erl(", io_lib:format("~p", [Any]), ")"] - end. - -inspect@bit_array(Bits) -> - Pieces = inspect@bit_array_pieces(Bits, []), - Inner = lists:join(", ", lists:reverse(Pieces)), - ["<<", Inner, ">>"]. - -inspect@bit_array_pieces(Bits, Acc) -> - case Bits of - <<>> -> - Acc; - <> -> - inspect@bit_array_pieces(Rest, [erlang:integer_to_binary(Byte) | Acc]); - _ -> - Size = erlang:bit_size(Bits), - <> = Bits, - SizeString = [":size(", erlang:integer_to_binary(Size), ")"], - Piece = [erlang:integer_to_binary(RemainingBits), SizeString], - [Piece | Acc] - end. - -inspect@binary(Binary) -> - case inspect@maybe_utf8_string(Binary, <<>>) of - {ok, InspectedUtf8String} -> - InspectedUtf8String; - {error, not_a_utf8_string} -> - Segments = [erlang:integer_to_list(X) || <> <= Binary], - ["<<", lists:join(", ", Segments), ">>"] - end. - -inspect@atom(Atom) -> - Binary = erlang:atom_to_binary(Atom), - case inspect@maybe_gleam_atom(Binary, none, <<>>) of - {ok, Inspected} -> Inspected; - {error, _} -> ["atom.create_from_string(\"", Binary, "\")"] - end. - -inspect@list(List) -> - case inspect@proper_or_improper_list(List) of - {proper, Elements} -> ["[", Elements, "]"]; - {improper, Elements} -> ["//erl([", Elements, "])"] - end. - -inspect@map(Map) -> - Fields = [ - [<<"#(">>, echo@inspect(Key), <<", ">>, echo@inspect(Value), <<")">>] - || {Key, Value} <- maps:to_list(Map) - ], - ["dict.from_list([", lists:join(", ", Fields), "])"]. - -inspect@record(Record) -> - [Atom | ArgsList] = erlang:tuple_to_list(Record), - Args = lists:join(", ", lists:map(fun echo@inspect/1, ArgsList)), - [echo@inspect(Atom), "(", Args, ")"]. - -inspect@tuple(Tuple) -> - Elements = lists:map(fun echo@inspect/1, erlang:tuple_to_list(Tuple)), - ["#(", lists:join(", ", Elements), ")"]. - -inspect@function(Function) -> - {arity, Arity} = erlang:fun_info(Function, arity), - ArgsAsciiCodes = lists:seq($a, $a + Arity - 1), - Args = lists:join(", ", lists:map(fun(Arg) -> <> end, ArgsAsciiCodes)), - ["//fn(", Args, ") { ... }"]. - -inspect@maybe_utf8_string(Binary, Acc) -> - case Binary of - <<>> -> - {ok, <<$", Acc/binary, $">>}; - <> -> - Escaped = inspect@escape_grapheme(First), - inspect@maybe_utf8_string(Rest, <>); - _ -> - {error, not_a_utf8_string} - end. - -inspect@escape_grapheme(Char) -> - case Char of - $" -> <<$\\, $">>; - $\\ -> <<$\\, $\\>>; - $\r -> <<$\\, $r>>; - $\n -> <<$\\, $n>>; - $\t -> <<$\\, $t>>; - $\f -> <<$\\, $f>>; - X when X > 126, X < 160 -> inspect@convert_to_u(X); - X when X < 32 -> inspect@convert_to_u(X); - Other -> <> - end. - -inspect@convert_to_u(Code) -> - erlang:list_to_binary(io_lib:format("\\u{~4.16.0B}", [Code])). - -inspect@proper_or_improper_list(List) -> - case List of - [] -> - {proper, []}; - [First] -> - {proper, [echo@inspect(First)]}; - [First | Rest] when erlang:is_list(Rest) -> - {Kind, Inspected} = inspect@proper_or_improper_list(Rest), - {Kind, [echo@inspect(First), ", " | Inspected]}; - [First | ImproperRest] -> - {improper, [echo@inspect(First), " | ", echo@inspect(ImproperRest)]} - end. - -inspect@maybe_gleam_atom(Atom, PrevChar, Acc) -> - case {Atom, PrevChar} of - {<<>>, none} -> - {error, nil}; - {<>, none} when ?is_digit_char(First) -> - {error, nil}; - {<<"_", _/binary>>, none} -> - {error, nil}; - {<<"_">>, _} -> - {error, nil}; - {<<"_", _/binary>>, $_} -> - {error, nil}; - {<>, _} when not ?is_atom_char(First) -> - {error, nil}; - {<>, none} -> - inspect@maybe_gleam_atom(Rest, First, <>); - {<<"_", Rest/binary>>, _} -> - inspect@maybe_gleam_atom(Rest, $_, Acc); - {<>, $_} -> - inspect@maybe_gleam_atom(Rest, First, <>); - {<>, _} -> - inspect@maybe_gleam_atom(Rest, First, <>); - {<<>>, _} -> - {ok, Acc}; - _ -> - erlang:throw({gleam_error, echo, Atom, PrevChar, Acc}) - end. - -inspect@uppercase(X) -> X - 32. - diff --git a/test-output/cases/echo_custom_type/build/dev/erlang/echo_custom_type/ebin/echo_custom_type.app b/test-output/cases/echo_custom_type/build/dev/erlang/echo_custom_type/ebin/echo_custom_type.app deleted file mode 100644 index 88ffb4c34db..00000000000 --- a/test-output/cases/echo_custom_type/build/dev/erlang/echo_custom_type/ebin/echo_custom_type.app +++ /dev/null @@ -1,7 +0,0 @@ -{application, echo_custom_type, [ - {vsn, "1.0.0"}, - {applications, []}, - {description, ""}, - {modules, [main]}, - {registered, []} -]}. diff --git a/test-output/cases/echo_custom_type/build/dev/erlang/echo_custom_type/include/main_Wibble.hrl b/test-output/cases/echo_custom_type/build/dev/erlang/echo_custom_type/include/main_Wibble.hrl deleted file mode 100644 index 2058efcd27c..00000000000 --- a/test-output/cases/echo_custom_type/build/dev/erlang/echo_custom_type/include/main_Wibble.hrl +++ /dev/null @@ -1 +0,0 @@ --record(wibble, {a :: integer(), b :: binary()}). diff --git a/test-output/cases/echo_custom_type/build/dev/erlang/echo_custom_type/include/main_Wobble.hrl b/test-output/cases/echo_custom_type/build/dev/erlang/echo_custom_type/include/main_Wobble.hrl deleted file mode 100644 index 88d7064fcbc..00000000000 --- a/test-output/cases/echo_custom_type/build/dev/erlang/echo_custom_type/include/main_Wobble.hrl +++ /dev/null @@ -1 +0,0 @@ --record(wobble, {a :: list(float())}). diff --git a/test-output/cases/echo_custom_type/build/dev/erlang/gleam_version b/test-output/cases/echo_custom_type/build/dev/erlang/gleam_version deleted file mode 100644 index 3e1ad720b13..00000000000 --- a/test-output/cases/echo_custom_type/build/dev/erlang/gleam_version +++ /dev/null @@ -1 +0,0 @@ -1.5.0 \ No newline at end of file diff --git a/test-output/cases/echo_custom_type/build/dev/javascript/echo_custom_type/_gleam_artefacts/main.cache b/test-output/cases/echo_custom_type/build/dev/javascript/echo_custom_type/_gleam_artefacts/main.cache deleted file mode 100644 index 4d316e22aa9..00000000000 Binary files a/test-output/cases/echo_custom_type/build/dev/javascript/echo_custom_type/_gleam_artefacts/main.cache and /dev/null differ diff --git a/test-output/cases/echo_custom_type/build/dev/javascript/echo_custom_type/_gleam_artefacts/main.cache_meta b/test-output/cases/echo_custom_type/build/dev/javascript/echo_custom_type/_gleam_artefacts/main.cache_meta deleted file mode 100644 index 9587e761d0a..00000000000 Binary files a/test-output/cases/echo_custom_type/build/dev/javascript/echo_custom_type/_gleam_artefacts/main.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_custom_type/build/dev/javascript/echo_custom_type/_gleam_artefacts/main.cache_warnings b/test-output/cases/echo_custom_type/build/dev/javascript/echo_custom_type/_gleam_artefacts/main.cache_warnings deleted file mode 100644 index 1b1cb4d44c5..00000000000 Binary files a/test-output/cases/echo_custom_type/build/dev/javascript/echo_custom_type/_gleam_artefacts/main.cache_warnings and /dev/null differ diff --git a/test-output/cases/echo_custom_type/build/dev/javascript/echo_custom_type/gleam.main.mjs b/test-output/cases/echo_custom_type/build/dev/javascript/echo_custom_type/gleam.main.mjs deleted file mode 100644 index e230911e646..00000000000 --- a/test-output/cases/echo_custom_type/build/dev/javascript/echo_custom_type/gleam.main.mjs +++ /dev/null @@ -1,2 +0,0 @@ -import { main } from "./main.mjs"; -main(); diff --git a/test-output/cases/echo_custom_type/build/dev/javascript/echo_custom_type/gleam.mjs b/test-output/cases/echo_custom_type/build/dev/javascript/echo_custom_type/gleam.mjs deleted file mode 100644 index 197cbbc35d4..00000000000 --- a/test-output/cases/echo_custom_type/build/dev/javascript/echo_custom_type/gleam.mjs +++ /dev/null @@ -1 +0,0 @@ -export * from "../prelude.mjs"; diff --git a/test-output/cases/echo_custom_type/build/dev/javascript/echo_custom_type/main.mjs b/test-output/cases/echo_custom_type/build/dev/javascript/echo_custom_type/main.mjs deleted file mode 100644 index 6e2b2b26926..00000000000 --- a/test-output/cases/echo_custom_type/build/dev/javascript/echo_custom_type/main.mjs +++ /dev/null @@ -1,147 +0,0 @@ -import { - toList, - CustomType as $CustomType, - BitArray as $BitArray, - List as $List, - UtfCodepoint as $UtfCodepoint, -} from "./gleam.mjs"; - -export class Wibble extends $CustomType { - constructor(a, b) { - super(); - this.a = a; - this.b = b; - } -} - -export class Wobble extends $CustomType { - constructor(a) { - super(); - this.a = a; - } -} - -export class Woo extends $CustomType {} - -export function main() { - echo(new Wibble(1, "hello"), "src/main.gleam", 8); - echo(new Wobble(toList([1.0, 1.1])), "src/main.gleam", 9); - return echo(new Woo(), "src/main.gleam", 10); -} - -function echo(value, file, line) { - const grey = "\u001b[90m"; - const reset_color = "\u001b[39m"; - const file_line = `${file}:${line}`; - const string_value = echo$inspect(value); - - if (typeof process === "object" && process.stderr?.write) { - // If we're in Node.js, use `stderr` - const string = `${grey}${file_line}${reset_color}\n${string_value}\n`; - process.stderr.write(string); - } else if (typeof Deno === "object") { - // If we're in Deno, use `stderr` - const string = `${grey}${file_line}${reset_color}\n${string_value}\n`; - Deno.stderr.writeSync(new TextEncoder().encode(string)); - } else { - // Otherwise, use `console.log` - // The browser's console.log doesn't support ansi escape codes - const string = `${file_line}\n${string_value}`; - console.log(string); - } - - return value; -} - -function echo$inspectString(str) { - let new_str = '"'; - for (let i = 0; i < str.length; i++) { - let char = str[i]; - if (char == "\n") new_str += "\\n"; - else if (char == "\r") new_str += "\\r"; - else if (char == "\t") new_str += "\\t"; - else if (char == "\f") new_str += "\\f"; - else if (char == "\\") new_str += "\\\\"; - else if (char == '"') new_str += '\\"'; - else if (char < " " || (char > "~" && char < "\u{00A0}")) { - new_str += "\\u{" + char.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0") + "}"; - } else { - new_str += char; - } - } - new_str += '"'; - return new_str; -} - -function echo$inspectDict(map) { - let body = "dict.from_list(["; - let first = true; - map.forEach((value, key) => { - if (!first) body = body + ", "; - body = body + "#(" + echo$inspect(key) + ", " + echo$inspect(value) + ")"; - first = false; - }); - return body + "])"; -} - -function echo$inspectCustomType(record) { - const props = Object.keys(record) - .map((label) => { - const value = echo$inspect(record[label]); - return isNaN(parseInt(label)) ? `${label}: ${value}` : value; - }) - .join(", "); - return props ? `${record.constructor.name}(${props})` : record.constructor.name; -} - -function echo$inspectObject(v) { - const name = Object.getPrototypeOf(v)?.constructor?.name || "Object"; - const props = []; - for (const k of Object.keys(v)) { - props.push(`${echo$inspect(k)}: ${echo$inspect(v[k])}`); - } - const body = props.length ? " " + props.join(", ") + " " : ""; - const head = name === "Object" ? "" : name + " "; - return `//js(${head}{${body}})`; -} - -function echo$inspect(v) { - const t = typeof v; - if (v === true) return "True"; - if (v === false) return "False"; - if (v === null) return "//js(null)"; - if (v === undefined) return "Nil"; - if (t === "string") return echo$inspectString(v); - if (t === "bigint" || t === "number") return v.toString(); - if (Array.isArray(v)) return `#(${v.map(echo$inspect).join(", ")})`; - if (v instanceof $List) return `[${v.toArray().map(echo$inspect).join(", ")}]`; - if (v instanceof $UtfCodepoint) return `//utfcodepoint(${String.fromCodePoint(v.value)})`; - if (v instanceof $BitArray) return `<<${Array.from(v.buffer).join(", ")}>>`; - if (v instanceof $CustomType) return echo$inspectCustomType(v); - if (echo$isDict(v)) return echo$inspectDict(v); - if (v instanceof Set) return `//js(Set(${[...v].map(echo$inspect).join(", ")}))`; - if (v instanceof RegExp) return `//js(${v})`; - if (v instanceof Date) return `//js(Date("${v.toISOString()}"))`; - if (v instanceof Function) { - const args = []; - for (const i of Array(v.length).keys()) args.push(String.fromCharCode(i + 97)); - return `//fn(${args.join(", ")}) { ... }`; - } - return echo$inspectObject(v); -} - -function echo$isDict(value) { - try { - // We can only check if an object is a stdlib Dict if it is one of the - // project's dependencies. - // The `Dict` class is the default export of `stdlib/dict.mjs` - // that we import as `$stdlib$dict`. - return value instanceof $stdlib$dict.default; - } catch { - // If stdlib is not one of the project's dependencies then `$stdlib$dict` - // will not have been imported and the check will throw an exception meaning - // we can't check if something is actually a `Dict`. - return false; - } -} - diff --git a/test-output/cases/echo_custom_type/build/dev/javascript/gleam_version b/test-output/cases/echo_custom_type/build/dev/javascript/gleam_version deleted file mode 100644 index 3e1ad720b13..00000000000 --- a/test-output/cases/echo_custom_type/build/dev/javascript/gleam_version +++ /dev/null @@ -1 +0,0 @@ -1.5.0 \ No newline at end of file diff --git a/test-output/cases/echo_custom_type/build/dev/javascript/prelude.mjs b/test-output/cases/echo_custom_type/build/dev/javascript/prelude.mjs deleted file mode 100644 index d2adeef273f..00000000000 --- a/test-output/cases/echo_custom_type/build/dev/javascript/prelude.mjs +++ /dev/null @@ -1,455 +0,0 @@ -// Values marked with @internal are not part of the public API and may change -// without notice. - -export class CustomType { - withFields(fields) { - let properties = Object.keys(this).map((label) => - label in fields ? fields[label] : this[label], - ); - return new this.constructor(...properties); - } -} - -export class List { - static fromArray(array, tail) { - let t = tail || new Empty(); - for (let i = array.length - 1; i >= 0; --i) { - t = new NonEmpty(array[i], t); - } - return t; - } - - [Symbol.iterator]() { - return new ListIterator(this); - } - - toArray() { - return [...this]; - } - - // @internal - atLeastLength(desired) { - for (let _ of this) { - if (desired <= 0) return true; - desired--; - } - return desired <= 0; - } - - // @internal - hasLength(desired) { - for (let _ of this) { - if (desired <= 0) return false; - desired--; - } - return desired === 0; - } - - // @internal - countLength() { - let length = 0; - for (let _ of this) length++; - return length; - } -} - -// @internal -export function prepend(element, tail) { - return new NonEmpty(element, tail); -} - -export function toList(elements, tail) { - return List.fromArray(elements, tail); -} - -// @internal -class ListIterator { - #current; - - constructor(current) { - this.#current = current; - } - - next() { - if (this.#current instanceof Empty) { - return { done: true }; - } else { - let { head, tail } = this.#current; - this.#current = tail; - return { value: head, done: false }; - } - } -} - -export class Empty extends List {} - -export class NonEmpty extends List { - constructor(head, tail) { - super(); - this.head = head; - this.tail = tail; - } -} - -export class BitArray { - constructor(buffer) { - if (!(buffer instanceof Uint8Array)) { - throw "BitArray can only be constructed from a Uint8Array"; - } - this.buffer = buffer; - } - - // @internal - get length() { - return this.buffer.length; - } - - // @internal - byteAt(index) { - return this.buffer[index]; - } - - // @internal - floatFromSlice(start, end, isBigEndian) { - return byteArrayToFloat(this.buffer, start, end, isBigEndian); - } - - // @internal - intFromSlice(start, end, isBigEndian, isSigned) { - return byteArrayToInt(this.buffer, start, end, isBigEndian, isSigned); - } - - // @internal - binaryFromSlice(start, end) { - return new BitArray(this.buffer.slice(start, end)); - } - - // @internal - sliceAfter(index) { - return new BitArray(this.buffer.slice(index)); - } -} - -export class UtfCodepoint { - constructor(value) { - this.value = value; - } -} - -// @internal -export function toBitArray(segments) { - if (segments.length === 0) { - return new BitArray(new Uint8Array()); - } - - if (segments.length === 1) { - // When there is a single Uint8Array segment, pass it directly to the bit - // array constructor to avoid a copy - if (segments[0] instanceof Uint8Array) { - return new BitArray(segments[0]); - } - - return new BitArray(new Uint8Array(segments)); - } - - // Count the total number of bytes, and check if there are any Uint8Array - // segments - let bytes = 0; - let hasUint8ArraySegment = false; - for (const segment of segments) { - if (segment instanceof Uint8Array) { - bytes += segment.byteLength; - hasUint8ArraySegment = true; - } else { - bytes++; - } - } - - // If there aren't any Uint8Array segments then pass the segments array - // directly to the Uint8Array constructor - if (!hasUint8ArraySegment) { - return new BitArray(new Uint8Array(segments)); - } - - // Copy the segments into a Uint8Array - let u8Array = new Uint8Array(bytes); - let cursor = 0; - for (let segment of segments) { - if (segment instanceof Uint8Array) { - u8Array.set(segment, cursor); - cursor += segment.byteLength; - } else { - u8Array[cursor] = segment; - cursor++; - } - } - - return new BitArray(u8Array); -} - -// @internal -// Derived from this answer https://stackoverflow.com/questions/8482309/converting-javascript-integer-to-byte-array-and-back -export function sizedInt(value, size, isBigEndian) { - if (size < 0) { - return new Uint8Array(); - } - if (size % 8 != 0) { - const msg = `Bit arrays must be byte aligned on JavaScript, got size of ${size} bits`; - throw new globalThis.Error(msg); - } - - const byteArray = new Uint8Array(size / 8); - - // Convert negative number to two's complement representation - if (value < 0) { - value = 2 ** size + value; - } - - if (isBigEndian) { - for (let i = byteArray.length - 1; i >= 0; i--) { - const byte = value % 256; - byteArray[i] = byte; - value = (value - byte) / 256; - } - } else { - for (let i = 0; i < byteArray.length; i++) { - const byte = value % 256; - byteArray[i] = byte; - value = (value - byte) / 256; - } - } - - return byteArray; -} - -// @internal -export function byteArrayToInt(byteArray, start, end, isBigEndian, isSigned) { - let value = 0; - - // Read bytes as an unsigned integer value - if (isBigEndian) { - for (let i = start; i < end; i++) { - value = value * 256 + byteArray[i]; - } - } else { - for (let i = end - 1; i >= start; i--) { - value = value * 256 + byteArray[i]; - } - } - - if (isSigned) { - const byteSize = end - start; - - const highBit = 2 ** (byteSize * 8 - 1); - - // If the high bit is set and this is a signed integer, reinterpret as - // two's complement - if (value >= highBit) { - value -= highBit * 2; - } - } - - return value; -} - -// @internal -export function byteArrayToFloat(byteArray, start, end, isBigEndian) { - const view = new DataView(byteArray.buffer); - - const byteSize = end - start; - - if (byteSize === 8) { - return view.getFloat64(start, !isBigEndian); - } else if (byteSize === 4) { - return view.getFloat32(start, !isBigEndian); - } else { - const msg = `Sized floats must be 32-bit or 64-bit on JavaScript, got size of ${byteSize * 8} bits`; - throw new globalThis.Error(msg); - } -} - -// @internal -export function stringBits(string) { - return new TextEncoder().encode(string); -} - -// @internal -export function codepointBits(codepoint) { - return stringBits(String.fromCodePoint(codepoint.value)); -} - -// @internal -export function sizedFloat(float, size, isBigEndian) { - if (size !== 32 && size !== 64) { - const msg = `Sized floats must be 32-bit or 64-bit on JavaScript, got size of ${size} bits`; - throw new globalThis.Error(msg); - } - - const byteArray = new Uint8Array(size / 8); - - const view = new DataView(byteArray.buffer); - - if (size == 64) { - view.setFloat64(0, float, !isBigEndian); - } else if (size === 32) { - view.setFloat32(0, float, !isBigEndian); - } - - return byteArray; -} - -export class Result extends CustomType { - // @internal - static isResult(data) { - return data instanceof Result; - } -} - -export class Ok extends Result { - constructor(value) { - super(); - this[0] = value; - } - - // @internal - isOk() { - return true; - } -} - -export class Error extends Result { - constructor(detail) { - super(); - this[0] = detail; - } - - // @internal - isOk() { - return false; - } -} - -export function isEqual(x, y) { - let values = [x, y]; - - while (values.length) { - let a = values.pop(); - let b = values.pop(); - if (a === b) continue; - - if (!isObject(a) || !isObject(b)) return false; - let unequal = - !structurallyCompatibleObjects(a, b) || - unequalDates(a, b) || - unequalBuffers(a, b) || - unequalArrays(a, b) || - unequalMaps(a, b) || - unequalSets(a, b) || - unequalRegExps(a, b); - if (unequal) return false; - - const proto = Object.getPrototypeOf(a); - if (proto !== null && typeof proto.equals === "function") { - try { - if (a.equals(b)) continue; - else return false; - } catch {} - } - - let [keys, get] = getters(a); - for (let k of keys(a)) { - values.push(get(a, k), get(b, k)); - } - } - - return true; -} - -function getters(object) { - if (object instanceof Map) { - return [(x) => x.keys(), (x, y) => x.get(y)]; - } else { - let extra = object instanceof globalThis.Error ? ["message"] : []; - return [(x) => [...extra, ...Object.keys(x)], (x, y) => x[y]]; - } -} - -function unequalDates(a, b) { - return a instanceof Date && (a > b || a < b); -} - -function unequalBuffers(a, b) { - return ( - a.buffer instanceof ArrayBuffer && - a.BYTES_PER_ELEMENT && - !(a.byteLength === b.byteLength && a.every((n, i) => n === b[i])) - ); -} - -function unequalArrays(a, b) { - return Array.isArray(a) && a.length !== b.length; -} - -function unequalMaps(a, b) { - return a instanceof Map && a.size !== b.size; -} - -function unequalSets(a, b) { - return ( - a instanceof Set && (a.size != b.size || [...a].some((e) => !b.has(e))) - ); -} - -function unequalRegExps(a, b) { - return a instanceof RegExp && (a.source !== b.source || a.flags !== b.flags); -} - -function isObject(a) { - return typeof a === "object" && a !== null; -} - -function structurallyCompatibleObjects(a, b) { - if (typeof a !== "object" && typeof b !== "object" && (!a || !b)) - return false; - - let nonstructural = [Promise, WeakSet, WeakMap, Function]; - if (nonstructural.some((c) => a instanceof c)) return false; - - return a.constructor === b.constructor; -} - -// @internal -export function remainderInt(a, b) { - if (b === 0) { - return 0; - } else { - return a % b; - } -} - -// @internal -export function divideInt(a, b) { - return Math.trunc(divideFloat(a, b)); -} - -// @internal -export function divideFloat(a, b) { - if (b === 0) { - return 0; - } else { - return a / b; - } -} - -// @internal -export function makeError(variant, module, line, fn, message, extra) { - let error = new globalThis.Error(message); - error.gleam_error = variant; - error.module = module; - error.line = line; - error.function = fn; - // TODO: Remove this with Gleam v2.0.0 - error.fn = fn; - for (let k in extra) error[k] = extra[k]; - return error; -} diff --git a/test-output/cases/echo_custom_type/build/packages/packages.toml b/test-output/cases/echo_custom_type/build/packages/packages.toml deleted file mode 100644 index e74c18552bb..00000000000 --- a/test-output/cases/echo_custom_type/build/packages/packages.toml +++ /dev/null @@ -1 +0,0 @@ -[packages] diff --git a/test-output/cases/echo_custom_type/manifest.toml b/test-output/cases/echo_custom_type/manifest.toml deleted file mode 100644 index c5d779a3f81..00000000000 --- a/test-output/cases/echo_custom_type/manifest.toml +++ /dev/null @@ -1,7 +0,0 @@ -# This file was generated by Gleam -# You typically do not need to edit this file - -packages = [ -] - -[requirements] diff --git a/test-output/cases/echo_dict/build/dev/erlang/echo_tuple/_gleam_artefacts/echo_tuple@@main.erl b/test-output/cases/echo_dict/build/dev/erlang/echo_tuple/_gleam_artefacts/echo_tuple@@main.erl deleted file mode 100644 index 8dcada176f1..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/echo_tuple/_gleam_artefacts/echo_tuple@@main.erl +++ /dev/null @@ -1,99 +0,0 @@ --module('echo_tuple@@main'). --export([run/1]). - --define(red, "\e[31;1m"). --define(grey, "\e[90m"). --define(reset_color, "\e[39m"). --define(reset_all, "\e[0m"). - -run(Module) -> - io:setopts(standard_io, [binary, {encoding, utf8}]), - io:setopts(standard_error, [{encoding, utf8}]), - process_flag(trap_exit, true), - Pid = spawn_link(fun() -> run_module(Module) end), - receive - {'EXIT', Pid, {Reason, StackTrace}} -> - print_error(exit, Reason, StackTrace), - init:stop(1) - end. - -run_module(Module) -> - try - {ok, _} = application:ensure_all_started('echo_tuple'), - erlang:process_flag(trap_exit, false), - Module:main(), - erlang:halt(0) - catch - Class:Reason:StackTrace -> - print_error(Class, Reason, StackTrace), - init:stop(1) - end. - -print_error(Class, Error, Stacktrace) -> - Printed = [ - ?red, "runtime error", ?reset_color, ": ", error_class(Class, Error), ?reset_all, - "\n\n", - error_message(Error), - "\n\n", - error_details(Class, Error), - "stacktrace:\n", - [error_frame(Line) || Line <- refine_first(Error, Stacktrace)] - ], - io:format(standard_error, "~ts~n", [Printed]). - -refine_first(#{gleam_error := _, line := L}, [{M, F, A, [{file, Fi} | _]} | S]) -> - [{M, F, A, [{file, Fi}, {line, L}]} | S]; -refine_first(_, S) -> - S. - -error_class(_, #{gleam_error := panic}) -> "panic"; -error_class(_, #{gleam_error := todo}) -> "todo"; -error_class(_, #{gleam_error := let_assert}) -> "let assert"; -error_class(Class, _) -> ["Erlang ", atom_to_binary(Class)]. - -error_message(#{gleam_error := _, message := M}) -> - M; -error_message(undef) -> - <<"A function was called but it did not exist."/utf8 >>; -error_message({case_clause, _}) -> - <<"No pattern matched in an Erlang case expression."/utf8>>; -error_message({badmatch, _}) -> - <<"An Erlang assignment pattern did not match."/utf8>>; -error_message(function_clause) -> - <<"No Erlang function clause matched the arguments it was called with."/utf8>>; -error_message(_) -> - <<"An error occurred outside of Gleam."/utf8>>. - -error_details(_, #{gleam_error := let_assert, value := V}) -> - ["unmatched value:\n ", print_term(V), $\n, $\n]; -error_details(_, {case_clause, V}) -> - ["unmatched value:\n ", print_term(V), $\n, $\n]; -error_details(_, {badmatch, V}) -> - ["unmatched value:\n ", print_term(V), $\n, $\n]; -error_details(_, #{gleam_error := _}) -> - []; -error_details(error, function_clause) -> - []; -error_details(error, undef) -> - []; -error_details(C, E) -> - ["erlang:", atom_to_binary(C), $(, print_term(E), $), $\n, $\n]. - -print_term(T) -> - try - gleam@string:inspect(T) - catch - _:_ -> io_lib:format("~p", [T]) - end. - -error_frame({?MODULE, _, _, _}) -> []; -error_frame({erl_eval, _, _, _}) -> []; -error_frame({init, _, _, _}) -> []; -error_frame({M, F, _, O}) -> - M1 = string:replace(atom_to_binary(M), "@", "/", all), - [" ", M1, $., atom_to_binary(F), error_frame_end(O), $\n]. - -error_frame_end([{file, Fi}, {line, L} | _]) -> - [?grey, $\s, Fi, $:, integer_to_binary(L), ?reset_all]; -error_frame_end(_) -> - [?grey, " unknown source", ?reset_all]. \ No newline at end of file diff --git a/test-output/cases/echo_dict/build/dev/erlang/echo_tuple/_gleam_artefacts/main.cache b/test-output/cases/echo_dict/build/dev/erlang/echo_tuple/_gleam_artefacts/main.cache deleted file mode 100644 index 6a7e2d1266c..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/echo_tuple/_gleam_artefacts/main.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/echo_tuple/_gleam_artefacts/main.cache_meta b/test-output/cases/echo_dict/build/dev/erlang/echo_tuple/_gleam_artefacts/main.cache_meta deleted file mode 100644 index 575cfd6de40..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/echo_tuple/_gleam_artefacts/main.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/echo_tuple/_gleam_artefacts/main.cache_warnings b/test-output/cases/echo_dict/build/dev/erlang/echo_tuple/_gleam_artefacts/main.cache_warnings deleted file mode 100644 index 1b1cb4d44c5..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/echo_tuple/_gleam_artefacts/main.cache_warnings and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/echo_tuple/_gleam_artefacts/main.erl b/test-output/cases/echo_dict/build/dev/erlang/echo_tuple/_gleam_artefacts/main.erl deleted file mode 100644 index fd3141a68d0..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/echo_tuple/_gleam_artefacts/main.erl +++ /dev/null @@ -1,194 +0,0 @@ --module(main). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([main/0]). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/src/main.gleam", 3). --spec main() -> gleam@dict:dict(integer(), binary()). -main() -> - echo(gleam@dict:new(), "src/main.gleam", 4), - echo( - maps:from_list([{1, <<"hello"/utf8>>}, {2, <<"world!"/utf8>>}]), - "src/main.gleam", - 5 - ). - --define(is_lowercase_char(X), (X > 96 andalso X < 123)). --define(is_underscore_char(X), (X == 95)). --define(is_digit_char(X), (X > 47 andalso X < 58)). --define(could_be_record(Tuple), - erlang:is_tuple(Tuple) andalso - erlang:is_atom(erlang:element(1, Tuple)) andalso - erlang:element(1, Tuple) =/= false andalso - erlang:element(1, Tuple) =/= true andalso - erlang:element(1, Tuple) =/= nil -). --define(is_atom_char(C), - (?is_lowercase_char(C) orelse - ?is_underscore_char(C) orelse - ?is_digit_char(C)) -). - --define(grey, "\e[90m"). --define(reset_color, "\e[39m"). - -echo(Value, File, Line) -> - StringLine = erlang:integer_to_list(Line), - StringValue = echo@inspect(Value), - io:put_chars( - standard_error, - [?grey, File, $:, StringLine, ?reset_color, $\n, StringValue, $\n] - ), - Value. - -echo@inspect(Value) -> - case Value of - nil -> "Nil"; - true -> "True"; - false -> "False"; - Int when erlang:is_integer(Int) -> erlang:integer_to_list(Int); - Float when erlang:is_float(Float) -> io_lib_format:fwrite_g(Float); - Binary when erlang:is_binary(Binary) -> inspect@binary(Binary); - Bits when erlang:is_bitstring(Bits) -> inspect@bit_array(Bits); - Atom when erlang:is_atom(Atom) -> inspect@atom(Atom); - List when erlang:is_list(List) -> inspect@list(List); - Map when erlang:is_map(Map) -> inspect@map(Map); - Record when ?could_be_record(Record) -> inspect@record(Record); - Tuple when erlang:is_tuple(Tuple) -> inspect@tuple(Tuple); - Function when erlang:is_function(Function) -> inspect@function(Function); - Any -> ["//erl(", io_lib:format("~p", [Any]), ")"] - end. - -inspect@bit_array(Bits) -> - Pieces = inspect@bit_array_pieces(Bits, []), - Inner = lists:join(", ", lists:reverse(Pieces)), - ["<<", Inner, ">>"]. - -inspect@bit_array_pieces(Bits, Acc) -> - case Bits of - <<>> -> - Acc; - <> -> - inspect@bit_array_pieces(Rest, [erlang:integer_to_binary(Byte) | Acc]); - _ -> - Size = erlang:bit_size(Bits), - <> = Bits, - SizeString = [":size(", erlang:integer_to_binary(Size), ")"], - Piece = [erlang:integer_to_binary(RemainingBits), SizeString], - [Piece | Acc] - end. - -inspect@binary(Binary) -> - case inspect@maybe_utf8_string(Binary, <<>>) of - {ok, InspectedUtf8String} -> - InspectedUtf8String; - {error, not_a_utf8_string} -> - Segments = [erlang:integer_to_list(X) || <> <= Binary], - ["<<", lists:join(", ", Segments), ">>"] - end. - -inspect@atom(Atom) -> - Binary = erlang:atom_to_binary(Atom), - case inspect@maybe_gleam_atom(Binary, none, <<>>) of - {ok, Inspected} -> Inspected; - {error, _} -> ["atom.create_from_string(\"", Binary, "\")"] - end. - -inspect@list(List) -> - case inspect@proper_or_improper_list(List) of - {proper, Elements} -> ["[", Elements, "]"]; - {improper, Elements} -> ["//erl([", Elements, "])"] - end. - -inspect@map(Map) -> - Fields = [ - [<<"#(">>, echo@inspect(Key), <<", ">>, echo@inspect(Value), <<")">>] - || {Key, Value} <- maps:to_list(Map) - ], - ["dict.from_list([", lists:join(", ", Fields), "])"]. - -inspect@record(Record) -> - [Atom | ArgsList] = erlang:tuple_to_list(Record), - Args = lists:join(", ", lists:map(fun echo@inspect/1, ArgsList)), - [echo@inspect(Atom), "(", Args, ")"]. - -inspect@tuple(Tuple) -> - Elements = lists:map(fun echo@inspect/1, erlang:tuple_to_list(Tuple)), - ["#(", lists:join(", ", Elements), ")"]. - -inspect@function(Function) -> - {arity, Arity} = erlang:fun_info(Function, arity), - ArgsAsciiCodes = lists:seq($a, $a + Arity - 1), - Args = lists:join(", ", lists:map(fun(Arg) -> <> end, ArgsAsciiCodes)), - ["//fn(", Args, ") { ... }"]. - -inspect@maybe_utf8_string(Binary, Acc) -> - case Binary of - <<>> -> - {ok, <<$", Acc/binary, $">>}; - <> -> - Escaped = inspect@escape_grapheme(First), - inspect@maybe_utf8_string(Rest, <>); - _ -> - {error, not_a_utf8_string} - end. - -inspect@escape_grapheme(Char) -> - case Char of - $" -> <<$\\, $">>; - $\\ -> <<$\\, $\\>>; - $\r -> <<$\\, $r>>; - $\n -> <<$\\, $n>>; - $\t -> <<$\\, $t>>; - $\f -> <<$\\, $f>>; - X when X > 126, X < 160 -> inspect@convert_to_u(X); - X when X < 32 -> inspect@convert_to_u(X); - Other -> <> - end. - -inspect@convert_to_u(Code) -> - erlang:list_to_binary(io_lib:format("\\u{~4.16.0B}", [Code])). - -inspect@proper_or_improper_list(List) -> - case List of - [] -> - {proper, []}; - [First] -> - {proper, [echo@inspect(First)]}; - [First | Rest] when erlang:is_list(Rest) -> - {Kind, Inspected} = inspect@proper_or_improper_list(Rest), - {Kind, [echo@inspect(First), ", " | Inspected]}; - [First | ImproperRest] -> - {improper, [echo@inspect(First), " | ", echo@inspect(ImproperRest)]} - end. - -inspect@maybe_gleam_atom(Atom, PrevChar, Acc) -> - case {Atom, PrevChar} of - {<<>>, none} -> - {error, nil}; - {<>, none} when ?is_digit_char(First) -> - {error, nil}; - {<<"_", _/binary>>, none} -> - {error, nil}; - {<<"_">>, _} -> - {error, nil}; - {<<"_", _/binary>>, $_} -> - {error, nil}; - {<>, _} when not ?is_atom_char(First) -> - {error, nil}; - {<>, none} -> - inspect@maybe_gleam_atom(Rest, First, <>); - {<<"_", Rest/binary>>, _} -> - inspect@maybe_gleam_atom(Rest, $_, Acc); - {<>, $_} -> - inspect@maybe_gleam_atom(Rest, First, <>); - {<>, _} -> - inspect@maybe_gleam_atom(Rest, First, <>); - {<<>>, _} -> - {ok, Acc}; - _ -> - erlang:throw({gleam_error, echo, Atom, PrevChar, Acc}) - end. - -inspect@uppercase(X) -> X - 32. - diff --git a/test-output/cases/echo_dict/build/dev/erlang/echo_tuple/ebin/echo_tuple.app b/test-output/cases/echo_dict/build/dev/erlang/echo_tuple/ebin/echo_tuple.app deleted file mode 100644 index 3547818ab1b..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/echo_tuple/ebin/echo_tuple.app +++ /dev/null @@ -1,7 +0,0 @@ -{application, echo_tuple, [ - {vsn, "1.0.0"}, - {applications, [gleam_stdlib]}, - {description, ""}, - {modules, [main]}, - {registered, []} -]}. diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/dict.mjs b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/dict.mjs deleted file mode 100644 index a8309e0cdbd..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/dict.mjs +++ /dev/null @@ -1,957 +0,0 @@ -/** - * This file uses jsdoc to annotate types. - * These types can be checked using the typescript compiler with "checkjs" option. - */ - -import { isEqual } from "./gleam.mjs"; - -const referenceMap = new WeakMap(); -const tempDataView = new DataView(new ArrayBuffer(8)); -let referenceUID = 0; -/** - * hash the object by reference using a weak map and incrementing uid - * @param {any} o - * @returns {number} - */ -function hashByReference(o) { - const known = referenceMap.get(o); - if (known !== undefined) { - return known; - } - const hash = referenceUID++; - if (referenceUID === 0x7fffffff) { - referenceUID = 0; - } - referenceMap.set(o, hash); - return hash; -} -/** - * merge two hashes in an order sensitive way - * @param {number} a - * @param {number} b - * @returns {number} - */ -function hashMerge(a, b) { - return (a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2))) | 0; -} -/** - * standard string hash popularised by java - * @param {string} s - * @returns {number} - */ -function hashString(s) { - let hash = 0; - const len = s.length; - for (let i = 0; i < len; i++) { - hash = (Math.imul(31, hash) + s.charCodeAt(i)) | 0; - } - return hash; -} -/** - * hash a number by converting to two integers and do some jumbling - * @param {number} n - * @returns {number} - */ -function hashNumber(n) { - tempDataView.setFloat64(0, n); - const i = tempDataView.getInt32(0); - const j = tempDataView.getInt32(4); - return Math.imul(0x45d9f3b, (i >> 16) ^ i) ^ j; -} -/** - * hash a BigInt by converting it to a string and hashing that - * @param {BigInt} n - * @returns {number} - */ -function hashBigInt(n) { - return hashString(n.toString()); -} -/** - * hash any js object - * @param {any} o - * @returns {number} - */ -function hashObject(o) { - const proto = Object.getPrototypeOf(o); - if (proto !== null && typeof proto.hashCode === "function") { - try { - const code = o.hashCode(o); - if (typeof code === "number") { - return code; - } - } catch {} - } - if (o instanceof Promise || o instanceof WeakSet || o instanceof WeakMap) { - return hashByReference(o); - } - if (o instanceof Date) { - return hashNumber(o.getTime()); - } - let h = 0; - if (o instanceof ArrayBuffer) { - o = new Uint8Array(o); - } - if (Array.isArray(o) || o instanceof Uint8Array) { - for (let i = 0; i < o.length; i++) { - h = (Math.imul(31, h) + getHash(o[i])) | 0; - } - } else if (o instanceof Set) { - o.forEach((v) => { - h = (h + getHash(v)) | 0; - }); - } else if (o instanceof Map) { - o.forEach((v, k) => { - h = (h + hashMerge(getHash(v), getHash(k))) | 0; - }); - } else { - const keys = Object.keys(o); - for (let i = 0; i < keys.length; i++) { - const k = keys[i]; - const v = o[k]; - h = (h + hashMerge(getHash(v), hashString(k))) | 0; - } - } - return h; -} -/** - * hash any js value - * @param {any} u - * @returns {number} - */ -export function getHash(u) { - if (u === null) return 0x42108422; - if (u === undefined) return 0x42108423; - if (u === true) return 0x42108421; - if (u === false) return 0x42108420; - switch (typeof u) { - case "number": - return hashNumber(u); - case "string": - return hashString(u); - case "bigint": - return hashBigInt(u); - case "object": - return hashObject(u); - case "symbol": - return hashByReference(u); - case "function": - return hashByReference(u); - default: - return 0; // should be unreachable - } -} -/** - * @template K,V - * @typedef {ArrayNode | IndexNode | CollisionNode} Node - */ -/** - * @template K,V - * @typedef {{ type: typeof ENTRY, k: K, v: V }} Entry - */ -/** - * @template K,V - * @typedef {{ type: typeof ARRAY_NODE, size: number, array: (undefined | Entry | Node)[] }} ArrayNode - */ -/** - * @template K,V - * @typedef {{ type: typeof INDEX_NODE, bitmap: number, array: (Entry | Node)[] }} IndexNode - */ -/** - * @template K,V - * @typedef {{ type: typeof COLLISION_NODE, hash: number, array: Entry[] }} CollisionNode - */ -/** - * @typedef {{ val: boolean }} Flag - */ -const SHIFT = 5; // number of bits you need to shift by to get the next bucket -const BUCKET_SIZE = Math.pow(2, SHIFT); -const MASK = BUCKET_SIZE - 1; // used to zero out all bits not in the bucket -const MAX_INDEX_NODE = BUCKET_SIZE / 2; // when does index node grow into array node -const MIN_ARRAY_NODE = BUCKET_SIZE / 4; // when does array node shrink to index node -const ENTRY = 0; -const ARRAY_NODE = 1; -const INDEX_NODE = 2; -const COLLISION_NODE = 3; -/** @type {IndexNode} */ -const EMPTY = { - type: INDEX_NODE, - bitmap: 0, - array: [], -}; -/** - * Mask the hash to get only the bucket corresponding to shift - * @param {number} hash - * @param {number} shift - * @returns {number} - */ -function mask(hash, shift) { - return (hash >>> shift) & MASK; -} -/** - * Set only the Nth bit where N is the masked hash - * @param {number} hash - * @param {number} shift - * @returns {number} - */ -function bitpos(hash, shift) { - return 1 << mask(hash, shift); -} -/** - * Count the number of 1 bits in a number - * @param {number} x - * @returns {number} - */ -function bitcount(x) { - x -= (x >> 1) & 0x55555555; - x = (x & 0x33333333) + ((x >> 2) & 0x33333333); - x = (x + (x >> 4)) & 0x0f0f0f0f; - x += x >> 8; - x += x >> 16; - return x & 0x7f; -} -/** - * Calculate the array index of an item in a bitmap index node - * @param {number} bitmap - * @param {number} bit - * @returns {number} - */ -function index(bitmap, bit) { - return bitcount(bitmap & (bit - 1)); -} -/** - * Efficiently copy an array and set one value at an index - * @template T - * @param {T[]} arr - * @param {number} at - * @param {T} val - * @returns {T[]} - */ -function cloneAndSet(arr, at, val) { - const len = arr.length; - const out = new Array(len); - for (let i = 0; i < len; ++i) { - out[i] = arr[i]; - } - out[at] = val; - return out; -} -/** - * Efficiently copy an array and insert one value at an index - * @template T - * @param {T[]} arr - * @param {number} at - * @param {T} val - * @returns {T[]} - */ -function spliceIn(arr, at, val) { - const len = arr.length; - const out = new Array(len + 1); - let i = 0; - let g = 0; - while (i < at) { - out[g++] = arr[i++]; - } - out[g++] = val; - while (i < len) { - out[g++] = arr[i++]; - } - return out; -} -/** - * Efficiently copy an array and remove one value at an index - * @template T - * @param {T[]} arr - * @param {number} at - * @returns {T[]} - */ -function spliceOut(arr, at) { - const len = arr.length; - const out = new Array(len - 1); - let i = 0; - let g = 0; - while (i < at) { - out[g++] = arr[i++]; - } - ++i; - while (i < len) { - out[g++] = arr[i++]; - } - return out; -} -/** - * Create a new node containing two entries - * @template K,V - * @param {number} shift - * @param {K} key1 - * @param {V} val1 - * @param {number} key2hash - * @param {K} key2 - * @param {V} val2 - * @returns {Node} - */ -function createNode(shift, key1, val1, key2hash, key2, val2) { - const key1hash = getHash(key1); - if (key1hash === key2hash) { - return { - type: COLLISION_NODE, - hash: key1hash, - array: [ - { type: ENTRY, k: key1, v: val1 }, - { type: ENTRY, k: key2, v: val2 }, - ], - }; - } - const addedLeaf = { val: false }; - return assoc( - assocIndex(EMPTY, shift, key1hash, key1, val1, addedLeaf), - shift, - key2hash, - key2, - val2, - addedLeaf - ); -} -/** - * @template T,K,V - * @callback AssocFunction - * @param {T} root - * @param {number} shift - * @param {number} hash - * @param {K} key - * @param {V} val - * @param {Flag} addedLeaf - * @returns {Node} - */ -/** - * Associate a node with a new entry, creating a new node - * @template T,K,V - * @type {AssocFunction,K,V>} - */ -function assoc(root, shift, hash, key, val, addedLeaf) { - switch (root.type) { - case ARRAY_NODE: - return assocArray(root, shift, hash, key, val, addedLeaf); - case INDEX_NODE: - return assocIndex(root, shift, hash, key, val, addedLeaf); - case COLLISION_NODE: - return assocCollision(root, shift, hash, key, val, addedLeaf); - } -} -/** - * @template T,K,V - * @type {AssocFunction,K,V>} - */ -function assocArray(root, shift, hash, key, val, addedLeaf) { - const idx = mask(hash, shift); - const node = root.array[idx]; - // if the corresponding index is empty set the index to a newly created node - if (node === undefined) { - addedLeaf.val = true; - return { - type: ARRAY_NODE, - size: root.size + 1, - array: cloneAndSet(root.array, idx, { type: ENTRY, k: key, v: val }), - }; - } - if (node.type === ENTRY) { - // if keys are equal replace the entry - if (isEqual(key, node.k)) { - if (val === node.v) { - return root; - } - return { - type: ARRAY_NODE, - size: root.size, - array: cloneAndSet(root.array, idx, { - type: ENTRY, - k: key, - v: val, - }), - }; - } - // otherwise upgrade the entry to a node and insert - addedLeaf.val = true; - return { - type: ARRAY_NODE, - size: root.size, - array: cloneAndSet( - root.array, - idx, - createNode(shift + SHIFT, node.k, node.v, hash, key, val) - ), - }; - } - // otherwise call assoc on the child node - const n = assoc(node, shift + SHIFT, hash, key, val, addedLeaf); - // if the child node hasn't changed just return the old root - if (n === node) { - return root; - } - // otherwise set the index to the new node - return { - type: ARRAY_NODE, - size: root.size, - array: cloneAndSet(root.array, idx, n), - }; -} -/** - * @template T,K,V - * @type {AssocFunction,K,V>} - */ -function assocIndex(root, shift, hash, key, val, addedLeaf) { - const bit = bitpos(hash, shift); - const idx = index(root.bitmap, bit); - // if there is already a item at this hash index.. - if ((root.bitmap & bit) !== 0) { - // if there is a node at the index (not an entry), call assoc on the child node - const node = root.array[idx]; - if (node.type !== ENTRY) { - const n = assoc(node, shift + SHIFT, hash, key, val, addedLeaf); - if (n === node) { - return root; - } - return { - type: INDEX_NODE, - bitmap: root.bitmap, - array: cloneAndSet(root.array, idx, n), - }; - } - // otherwise there is an entry at the index - // if the keys are equal replace the entry with the updated value - const nodeKey = node.k; - if (isEqual(key, nodeKey)) { - if (val === node.v) { - return root; - } - return { - type: INDEX_NODE, - bitmap: root.bitmap, - array: cloneAndSet(root.array, idx, { - type: ENTRY, - k: key, - v: val, - }), - }; - } - // if the keys are not equal, replace the entry with a new child node - addedLeaf.val = true; - return { - type: INDEX_NODE, - bitmap: root.bitmap, - array: cloneAndSet( - root.array, - idx, - createNode(shift + SHIFT, nodeKey, node.v, hash, key, val) - ), - }; - } else { - // else there is currently no item at the hash index - const n = root.array.length; - // if the number of nodes is at the maximum, expand this node into an array node - if (n >= MAX_INDEX_NODE) { - // create a 32 length array for the new array node (one for each bit in the hash) - const nodes = new Array(32); - // create and insert a node for the new entry - const jdx = mask(hash, shift); - nodes[jdx] = assocIndex(EMPTY, shift + SHIFT, hash, key, val, addedLeaf); - let j = 0; - let bitmap = root.bitmap; - // place each item in the index node into the correct spot in the array node - // loop through all 32 bits / array positions - for (let i = 0; i < 32; i++) { - if ((bitmap & 1) !== 0) { - const node = root.array[j++]; - nodes[i] = node; - } - // shift the bitmap to process the next bit - bitmap = bitmap >>> 1; - } - return { - type: ARRAY_NODE, - size: n + 1, - array: nodes, - }; - } else { - // else there is still space in this index node - // simply insert a new entry at the hash index - const newArray = spliceIn(root.array, idx, { - type: ENTRY, - k: key, - v: val, - }); - addedLeaf.val = true; - return { - type: INDEX_NODE, - bitmap: root.bitmap | bit, - array: newArray, - }; - } - } -} -/** - * @template T,K,V - * @type {AssocFunction,K,V>} - */ -function assocCollision(root, shift, hash, key, val, addedLeaf) { - // if there is a hash collision - if (hash === root.hash) { - const idx = collisionIndexOf(root, key); - // if this key already exists replace the entry with the new value - if (idx !== -1) { - const entry = root.array[idx]; - if (entry.v === val) { - return root; - } - return { - type: COLLISION_NODE, - hash: hash, - array: cloneAndSet(root.array, idx, { type: ENTRY, k: key, v: val }), - }; - } - // otherwise insert the entry at the end of the array - const size = root.array.length; - addedLeaf.val = true; - return { - type: COLLISION_NODE, - hash: hash, - array: cloneAndSet(root.array, size, { type: ENTRY, k: key, v: val }), - }; - } - // if there is no hash collision, upgrade to an index node - return assoc( - { - type: INDEX_NODE, - bitmap: bitpos(root.hash, shift), - array: [root], - }, - shift, - hash, - key, - val, - addedLeaf - ); -} -/** - * Find the index of a key in the collision node's array - * @template K,V - * @param {CollisionNode} root - * @param {K} key - * @returns {number} - */ -function collisionIndexOf(root, key) { - const size = root.array.length; - for (let i = 0; i < size; i++) { - if (isEqual(key, root.array[i].k)) { - return i; - } - } - return -1; -} -/** - * @template T,K,V - * @callback FindFunction - * @param {T} root - * @param {number} shift - * @param {number} hash - * @param {K} key - * @returns {undefined | Entry} - */ -/** - * Return the found entry or undefined if not present in the root - * @template K,V - * @type {FindFunction,K,V>} - */ -function find(root, shift, hash, key) { - switch (root.type) { - case ARRAY_NODE: - return findArray(root, shift, hash, key); - case INDEX_NODE: - return findIndex(root, shift, hash, key); - case COLLISION_NODE: - return findCollision(root, key); - } -} -/** - * @template K,V - * @type {FindFunction,K,V>} - */ -function findArray(root, shift, hash, key) { - const idx = mask(hash, shift); - const node = root.array[idx]; - if (node === undefined) { - return undefined; - } - if (node.type !== ENTRY) { - return find(node, shift + SHIFT, hash, key); - } - if (isEqual(key, node.k)) { - return node; - } - return undefined; -} -/** - * @template K,V - * @type {FindFunction,K,V>} - */ -function findIndex(root, shift, hash, key) { - const bit = bitpos(hash, shift); - if ((root.bitmap & bit) === 0) { - return undefined; - } - const idx = index(root.bitmap, bit); - const node = root.array[idx]; - if (node.type !== ENTRY) { - return find(node, shift + SHIFT, hash, key); - } - if (isEqual(key, node.k)) { - return node; - } - return undefined; -} -/** - * @template K,V - * @param {CollisionNode} root - * @param {K} key - * @returns {undefined | Entry} - */ -function findCollision(root, key) { - const idx = collisionIndexOf(root, key); - if (idx < 0) { - return undefined; - } - return root.array[idx]; -} -/** - * @template T,K,V - * @callback WithoutFunction - * @param {T} root - * @param {number} shift - * @param {number} hash - * @param {K} key - * @returns {undefined | Node} - */ -/** - * Remove an entry from the root, returning the updated root. - * Returns undefined if the node should be removed from the parent. - * @template K,V - * @type {WithoutFunction,K,V>} - * */ -function without(root, shift, hash, key) { - switch (root.type) { - case ARRAY_NODE: - return withoutArray(root, shift, hash, key); - case INDEX_NODE: - return withoutIndex(root, shift, hash, key); - case COLLISION_NODE: - return withoutCollision(root, key); - } -} -/** - * @template K,V - * @type {WithoutFunction,K,V>} - */ -function withoutArray(root, shift, hash, key) { - const idx = mask(hash, shift); - const node = root.array[idx]; - if (node === undefined) { - return root; // already empty - } - let n = undefined; - // if node is an entry and the keys are not equal there is nothing to remove - // if node is not an entry do a recursive call - if (node.type === ENTRY) { - if (!isEqual(node.k, key)) { - return root; // no changes - } - } else { - n = without(node, shift + SHIFT, hash, key); - if (n === node) { - return root; // no changes - } - } - // if the recursive call returned undefined the node should be removed - if (n === undefined) { - // if the number of child nodes is at the minimum, pack into an index node - if (root.size <= MIN_ARRAY_NODE) { - const arr = root.array; - const out = new Array(root.size - 1); - let i = 0; - let j = 0; - let bitmap = 0; - while (i < idx) { - const nv = arr[i]; - if (nv !== undefined) { - out[j] = nv; - bitmap |= 1 << i; - ++j; - } - ++i; - } - ++i; // skip copying the removed node - while (i < arr.length) { - const nv = arr[i]; - if (nv !== undefined) { - out[j] = nv; - bitmap |= 1 << i; - ++j; - } - ++i; - } - return { - type: INDEX_NODE, - bitmap: bitmap, - array: out, - }; - } - return { - type: ARRAY_NODE, - size: root.size - 1, - array: cloneAndSet(root.array, idx, n), - }; - } - return { - type: ARRAY_NODE, - size: root.size, - array: cloneAndSet(root.array, idx, n), - }; -} -/** - * @template K,V - * @type {WithoutFunction,K,V>} - */ -function withoutIndex(root, shift, hash, key) { - const bit = bitpos(hash, shift); - if ((root.bitmap & bit) === 0) { - return root; // already empty - } - const idx = index(root.bitmap, bit); - const node = root.array[idx]; - // if the item is not an entry - if (node.type !== ENTRY) { - const n = without(node, shift + SHIFT, hash, key); - if (n === node) { - return root; // no changes - } - // if not undefined, the child node still has items, so update it - if (n !== undefined) { - return { - type: INDEX_NODE, - bitmap: root.bitmap, - array: cloneAndSet(root.array, idx, n), - }; - } - // otherwise the child node should be removed - // if it was the only child node, remove this node from the parent - if (root.bitmap === bit) { - return undefined; - } - // otherwise just remove the child node - return { - type: INDEX_NODE, - bitmap: root.bitmap ^ bit, - array: spliceOut(root.array, idx), - }; - } - // otherwise the item is an entry, remove it if the key matches - if (isEqual(key, node.k)) { - if (root.bitmap === bit) { - return undefined; - } - return { - type: INDEX_NODE, - bitmap: root.bitmap ^ bit, - array: spliceOut(root.array, idx), - }; - } - return root; -} -/** - * @template K,V - * @param {CollisionNode} root - * @param {K} key - * @returns {undefined | Node} - */ -function withoutCollision(root, key) { - const idx = collisionIndexOf(root, key); - // if the key not found, no changes - if (idx < 0) { - return root; - } - // otherwise the entry was found, remove it - // if it was the only entry in this node, remove the whole node - if (root.array.length === 1) { - return undefined; - } - // otherwise just remove the entry - return { - type: COLLISION_NODE, - hash: root.hash, - array: spliceOut(root.array, idx), - }; -} -/** - * @template K,V - * @param {undefined | Node} root - * @param {(value:V,key:K)=>void} fn - * @returns {void} - */ -function forEach(root, fn) { - if (root === undefined) { - return; - } - const items = root.array; - const size = items.length; - for (let i = 0; i < size; i++) { - const item = items[i]; - if (item === undefined) { - continue; - } - if (item.type === ENTRY) { - fn(item.v, item.k); - continue; - } - forEach(item, fn); - } -} -/** - * Extra wrapper to keep track of Dict size and clean up the API - * @template K,V - */ -export default class Dict { - /** - * @template V - * @param {Record} o - * @returns {Dict} - */ - static fromObject(o) { - const keys = Object.keys(o); - /** @type Dict */ - let m = Dict.new(); - for (let i = 0; i < keys.length; i++) { - const k = keys[i]; - m = m.set(k, o[k]); - } - return m; - } - /** - * @template K,V - * @param {Map} o - * @returns {Dict} - */ - static fromMap(o) { - /** @type Dict */ - let m = Dict.new(); - o.forEach((v, k) => { - m = m.set(k, v); - }); - return m; - } - static new() { - return new Dict(undefined, 0); - } - /** - * @param {undefined | Node} root - * @param {number} size - */ - constructor(root, size) { - this.root = root; - this.size = size; - } - /** - * @template NotFound - * @param {K} key - * @param {NotFound} notFound - * @returns {NotFound | V} - */ - get(key, notFound) { - if (this.root === undefined) { - return notFound; - } - const found = find(this.root, 0, getHash(key), key); - if (found === undefined) { - return notFound; - } - return found.v; - } - /** - * @param {K} key - * @param {V} val - * @returns {Dict} - */ - set(key, val) { - const addedLeaf = { val: false }; - const root = this.root === undefined ? EMPTY : this.root; - const newRoot = assoc(root, 0, getHash(key), key, val, addedLeaf); - if (newRoot === this.root) { - return this; - } - return new Dict(newRoot, addedLeaf.val ? this.size + 1 : this.size); - } - /** - * @param {K} key - * @returns {Dict} - */ - delete(key) { - if (this.root === undefined) { - return this; - } - const newRoot = without(this.root, 0, getHash(key), key); - if (newRoot === this.root) { - return this; - } - if (newRoot === undefined) { - return Dict.new(); - } - return new Dict(newRoot, this.size - 1); - } - /** - * @param {K} key - * @returns {boolean} - */ - has(key) { - if (this.root === undefined) { - return false; - } - return find(this.root, 0, getHash(key), key) !== undefined; - } - /** - * @returns {[K,V][]} - */ - entries() { - if (this.root === undefined) { - return []; - } - /** @type [K,V][] */ - const result = []; - this.forEach((v, k) => result.push([k, v])); - return result; - } - /** - * - * @param {(val:V,key:K)=>void} fn - */ - forEach(fn) { - forEach(this.root, fn); - } - hashCode() { - let h = 0; - this.forEach((v, k) => { - h = (h + hashMerge(getHash(v), getHash(k))) | 0; - }); - return h; - } - /** - * @param {unknown} o - * @returns {boolean} - */ - equals(o) { - if (!(o instanceof Dict) || this.size !== o.size) { - return false; - } - let equal = true; - this.forEach((v, k) => { - equal = equal && isEqual(o.get(k, !v), v); - }); - return equal; - } -} diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@@compile.erl b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@@compile.erl deleted file mode 100644 index 3e0a645b737..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@@compile.erl +++ /dev/null @@ -1,163 +0,0 @@ -#!/usr/bin/env escript --mode(compile). - -% TODO: Don't concurrently print warnings and errors -% TODO: Some tests - -main(_) -> compile_package_loop(). - -compile_package_loop() -> - case file:read_line(standard_io) of - eof -> ok; - {ok, Line} -> - Chars = unicode:characters_to_list(Line), - {ok, Tokens, _} = erl_scan:string(Chars), - {ok, {Lib, Out, Modules}} = erl_parse:parse_term(Tokens), - case compile_package(Lib, Out, Modules) of - ok -> io:put_chars("gleam-compile-result-ok\n"); - err -> io:put_chars("gleam-compile-result-error\n") - end, - compile_package_loop() - end. - -compile_package(Lib, Out, Modules) -> - IsElixirModule = fun(Module) -> - filename:extension(Module) =:= ".ex" - end, - {ElixirModules, ErlangModules} = lists:partition(IsElixirModule, Modules), - ok = configure_logging(), - ok = add_lib_to_erlang_path(Lib), - ok = filelib:ensure_dir([Out, $/]), - {ErlangOk, _ErlangBeams} = compile_erlang(ErlangModules, Out), - {ElixirOk, _ElixirBeams} = case ErlangOk of - true -> compile_elixir(ElixirModules, Out); - false -> {false, []} - end, - ok = del_lib_from_erlang_path(Lib), - case ErlangOk and ElixirOk of - true -> ok; - false -> err - end. - -compile_erlang(Modules, Out) -> - Workers = start_compiler_workers(Out), - ok = producer_loop(Modules, Workers), - collect_results({true, []}). - -collect_results(Acc = {Result, Beams}) -> - receive - {compiled, Beam} -> collect_results({Result, [Beam | Beams]}); - failed -> collect_results({false, Beams}) - after 0 -> Acc - end. - -producer_loop([], 0) -> - ok; -producer_loop([], Workers) -> - receive - {work_please, _} -> producer_loop([], Workers - 1) - end; -producer_loop([Module | Modules], Workers) -> - receive - {work_please, Worker} -> - erlang:send(Worker, {module, Module}), - producer_loop(Modules, Workers) - end. - -start_compiler_workers(Out) -> - Parent = self(), - NumSchedulers = erlang:system_info(schedulers), - SpawnWorker = fun(_) -> - erlang:spawn_link(fun() -> worker_loop(Parent, Out) end) - end, - lists:foreach(SpawnWorker, lists:seq(1, NumSchedulers)), - NumSchedulers. - -worker_loop(Parent, Out) -> - Options = [report_errors, report_warnings, debug_info, {outdir, Out}], - erlang:send(Parent, {work_please, self()}), - receive - {module, Module} -> - log({compiling, Module}), - case compile:file(Module, Options) of - {ok, ModuleName} -> - Beam = filename:join(Out, ModuleName) ++ ".beam", - Message = {compiled, Beam}, - log(Message), - erlang:send(Parent, Message); - error -> - log({failed, Module}), - erlang:send(Parent, failed) - end, - worker_loop(Parent, Out) - end. - -compile_elixir(Modules, Out) -> - Error = [ - "The program elixir was not found. Is it installed?", - $\n, - "Documentation for installing Elixir can be viewed here:", - $\n, - "https://elixir-lang.org/install.html" - ], - case Modules of - [] -> {true, []}; - _ -> - log({starting, "compiler.app"}), - ok = application:start(compiler), - log({starting, "elixir.app"}), - case application:start(elixir) of - ok -> do_compile_elixir(Modules, Out); - _ -> - io:put_chars(standard_error, [Error, $\n]), - {false, []} - end - end. - -do_compile_elixir(Modules, Out) -> - ModuleBins = lists:map(fun(Module) -> - log({compiling, Module}), - list_to_binary(Module) - end, Modules), - OutBin = list_to_binary(Out), - Options = [{dest, OutBin}], - % Silence "redefining module" warnings. - % Compiled modules in the build directory are added to the code path. - % These warnings result from recompiling loaded modules. - % TODO: This line can likely be removed if/when the build directory is cleaned before every compilation. - 'Elixir.Code':compiler_options([{ignore_module_conflict, true}]), - case 'Elixir.Kernel.ParallelCompiler':compile_to_path(ModuleBins, OutBin, Options) of - {ok, ModuleAtoms, _} -> - ToBeam = fun(ModuleAtom) -> - Beam = filename:join(Out, atom_to_list(ModuleAtom)) ++ ".beam", - log({compiled, Beam}), - Beam - end, - {true, lists:map(ToBeam, ModuleAtoms)}; - {error, Errors, _} -> - % Log all filenames associated with modules that failed to compile. - % Note: The compiler prints compilation errors upon encountering them. - ErrorFiles = lists:usort([File || {File, _, _} <- Errors]), - Log = fun(File) -> - log({failed, binary_to_list(File)}) - end, - lists:foreach(Log, ErrorFiles), - {false, []}; - _ -> {false, []} - end. - -add_lib_to_erlang_path(Lib) -> - code:add_paths(filelib:wildcard([Lib, "/*/ebin"])). - -del_lib_from_erlang_path(Lib) -> - code:del_paths(filelib:wildcard([Lib, "/*/ebin"])). - -configure_logging() -> - Enabled = os:getenv("GLEAM_LOG") /= false, - persistent_term:put(gleam_logging_enabled, Enabled). - -log(Term) -> - case persistent_term:get(gleam_logging_enabled) of - true -> erlang:display(Term), ok; - false -> ok - end. diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@bit_array.cache b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@bit_array.cache deleted file mode 100644 index aad0e0861db..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@bit_array.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@bit_array.cache_meta b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@bit_array.cache_meta deleted file mode 100644 index 7d2e0a9e3d4..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@bit_array.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@bit_array.erl b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@bit_array.erl deleted file mode 100644 index c8659a98e8e..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@bit_array.erl +++ /dev/null @@ -1,213 +0,0 @@ --module(gleam@bit_array). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([from_string/1, byte_size/1, slice/3, is_utf8/1, to_string/1, concat/1, append/2, base64_encode/2, base64_decode/1, base64_url_encode/2, base64_url_decode/1, base16_encode/1, base16_decode/1, inspect/1, compare/2]). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bit_array.gleam", 11). --spec from_string(binary()) -> bitstring(). -from_string(X) -> - gleam_stdlib:identity(X). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bit_array.gleam", 17). --spec byte_size(bitstring()) -> integer(). -byte_size(X) -> - erlang:byte_size(X). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bit_array.gleam", 42). --spec slice(bitstring(), integer(), integer()) -> {ok, bitstring()} | - {error, nil}. -slice(String, Position, Length) -> - gleam_stdlib:bit_array_slice(String, Position, Length). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bit_array.gleam", 55). --spec do_is_utf8(bitstring()) -> boolean(). -do_is_utf8(Bits) -> - case Bits of - <<>> -> - true; - - <<_/utf8, Rest/binary>> -> - do_is_utf8(Rest); - - _ -> - false - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bit_array.gleam", 50). --spec is_utf8(bitstring()) -> boolean(). -is_utf8(Bits) -> - do_is_utf8(Bits). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bit_array.gleam", 83). --spec do_to_string(bitstring()) -> {ok, binary()} | {error, nil}. -do_to_string(Bits) -> - case is_utf8(Bits) of - true -> - {ok, gleam_stdlib:identity(Bits)}; - - false -> - {error, nil} - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bit_array.gleam", 75). --spec to_string(bitstring()) -> {ok, binary()} | {error, nil}. -to_string(Bits) -> - do_to_string(Bits). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bit_array.gleam", 101). --spec concat(list(bitstring())) -> bitstring(). -concat(Bit_arrays) -> - gleam_stdlib:bit_array_concat(Bit_arrays). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bit_array.gleam", 28). --spec append(bitstring(), bitstring()) -> bitstring(). -append(First, Second) -> - gleam_stdlib:bit_array_concat([First, Second]). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bit_array.gleam", 107). --spec base64_encode(bitstring(), boolean()) -> binary(). -base64_encode(Input, Padding) -> - gleam_stdlib:bit_array_base64_encode(Input, Padding). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bit_array.gleam", 111). --spec base64_decode(binary()) -> {ok, bitstring()} | {error, nil}. -base64_decode(Encoded) -> - Padded = case erlang:byte_size(gleam_stdlib:identity(Encoded)) rem 4 of - 0 -> - Encoded; - - N -> - gleam@string:append( - Encoded, - gleam@string:repeat(<<"="/utf8>>, 4 - N) - ) - end, - gleam_stdlib:base_decode64(Padded). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bit_array.gleam", 125). --spec base64_url_encode(bitstring(), boolean()) -> binary(). -base64_url_encode(Input, Padding) -> - _pipe = gleam_stdlib:bit_array_base64_encode(Input, Padding), - _pipe@1 = gleam@string:replace(_pipe, <<"+"/utf8>>, <<"-"/utf8>>), - gleam@string:replace(_pipe@1, <<"/"/utf8>>, <<"_"/utf8>>). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bit_array.gleam", 133). --spec base64_url_decode(binary()) -> {ok, bitstring()} | {error, nil}. -base64_url_decode(Encoded) -> - _pipe = Encoded, - _pipe@1 = gleam@string:replace(_pipe, <<"-"/utf8>>, <<"+"/utf8>>), - _pipe@2 = gleam@string:replace(_pipe@1, <<"_"/utf8>>, <<"/"/utf8>>), - base64_decode(_pipe@2). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bit_array.gleam", 142). --spec base16_encode(bitstring()) -> binary(). -base16_encode(Input) -> - binary:encode_hex(Input). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bit_array.gleam", 146). --spec base16_decode(binary()) -> {ok, bitstring()} | {error, nil}. -base16_decode(Input) -> - gleam_stdlib:base16_decode(Input). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bit_array.gleam", 165). --spec do_inspect(bitstring(), binary()) -> binary(). -do_inspect(Input, Accumulator) -> - case Input of - <<>> -> - Accumulator; - - <> -> - <<<>/binary, - ":size(1)"/utf8>>; - - <> -> - <<<>/binary, - ":size(2)"/utf8>>; - - <> -> - <<<>/binary, - ":size(3)"/utf8>>; - - <> -> - <<<>/binary, - ":size(4)"/utf8>>; - - <> -> - <<<>/binary, - ":size(5)"/utf8>>; - - <> -> - <<<>/binary, - ":size(6)"/utf8>>; - - <> -> - <<<>/binary, - ":size(7)"/utf8>>; - - <> -> - Suffix = case Rest of - <<>> -> - <<""/utf8>>; - - _ -> - <<", "/utf8>> - end, - Accumulator@1 = <<<>/binary, - Suffix/binary>>, - do_inspect(Rest, Accumulator@1); - - _ -> - Accumulator - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bit_array.gleam", 160). --spec inspect(bitstring()) -> binary(). -inspect(Input) -> - <<(do_inspect(Input, <<"<<"/utf8>>))/binary, ">>"/utf8>>. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bit_array.gleam", 210). --spec compare(bitstring(), bitstring()) -> gleam@order:order(). -compare(A, B) -> - case {A, B} of - {<>, - <>} -> - case {First_byte, Second_byte} of - {F, S} when F > S -> - gt; - - {F@1, S@1} when F@1 < S@1 -> - lt; - - {_, _} -> - compare(First_rest, Second_rest) - end; - - {<<>>, <<>>} -> - eq; - - {_, <<>>} -> - gt; - - {<<>>, _} -> - lt; - - {First, Second} -> - case {gleam_stdlib:bit_array_to_int_and_size(First), - gleam_stdlib:bit_array_to_int_and_size(Second)} of - {{A@1, _}, {B@1, _}} when A@1 > B@1 -> - gt; - - {{A@2, _}, {B@2, _}} when A@2 < B@2 -> - lt; - - {{_, Size_a}, {_, Size_b}} when Size_a > Size_b -> - gt; - - {{_, Size_a@1}, {_, Size_b@1}} when Size_a@1 < Size_b@1 -> - lt; - - {_, _} -> - eq - end - end. diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@bool.cache b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@bool.cache deleted file mode 100644 index e9b5b7f0ec9..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@bool.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@bool.cache_meta b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@bool.cache_meta deleted file mode 100644 index c0c214714a8..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@bool.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@bool.erl b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@bool.erl deleted file mode 100644 index f7d2d287a96..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@bool.erl +++ /dev/null @@ -1,100 +0,0 @@ --module(gleam@bool). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export(['and'/2, 'or'/2, negate/1, nor/2, nand/2, exclusive_or/2, exclusive_nor/2, compare/2, to_int/1, to_string/1, guard/3, lazy_guard/3]). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bool.gleam", 33). --spec 'and'(boolean(), boolean()) -> boolean(). -'and'(A, B) -> - A andalso B. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bool.gleam", 59). --spec 'or'(boolean(), boolean()) -> boolean(). -'or'(A, B) -> - A orelse B. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bool.gleam", 79). --spec negate(boolean()) -> boolean(). -negate(Bool) -> - not Bool. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bool.gleam", 107). --spec nor(boolean(), boolean()) -> boolean(). -nor(A, B) -> - not (A orelse B). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bool.gleam", 135). --spec nand(boolean(), boolean()) -> boolean(). -nand(A, B) -> - not (A andalso B). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bool.gleam", 163). --spec exclusive_or(boolean(), boolean()) -> boolean(). -exclusive_or(A, B) -> - A /= B. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bool.gleam", 191). --spec exclusive_nor(boolean(), boolean()) -> boolean(). -exclusive_nor(A, B) -> - A =:= B. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bool.gleam", 206). --spec compare(boolean(), boolean()) -> gleam@order:order(). -compare(A, B) -> - case {A, B} of - {true, true} -> - eq; - - {true, false} -> - gt; - - {false, false} -> - eq; - - {false, true} -> - lt - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bool.gleam", 229). --spec to_int(boolean()) -> integer(). -to_int(Bool) -> - case Bool of - false -> - 0; - - true -> - 1 - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bool.gleam", 250). --spec to_string(boolean()) -> binary(). -to_string(Bool) -> - case Bool of - false -> - <<"False"/utf8>>; - - true -> - <<"True"/utf8>> - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bool.gleam", 309). --spec guard(boolean(), BVG, fun(() -> BVG)) -> BVG. -guard(Requirement, Consequence, Alternative) -> - case Requirement of - true -> - Consequence; - - false -> - Alternative() - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bool.gleam", 350). --spec lazy_guard(boolean(), fun(() -> BVH), fun(() -> BVH)) -> BVH. -lazy_guard(Requirement, Consequence, Alternative) -> - case Requirement of - true -> - Consequence(); - - false -> - Alternative() - end. diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@bytes_builder.cache b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@bytes_builder.cache deleted file mode 100644 index 2639521faa0..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@bytes_builder.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@bytes_builder.cache_meta b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@bytes_builder.cache_meta deleted file mode 100644 index 60ef071c41c..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@bytes_builder.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@bytes_builder.erl b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@bytes_builder.erl deleted file mode 100644 index 46f5857f8ec..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@bytes_builder.erl +++ /dev/null @@ -1,102 +0,0 @@ --module(gleam@bytes_builder). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([append_builder/2, prepend_builder/2, concat/1, new/0, from_string/1, prepend_string/2, append_string/2, from_string_builder/1, from_bit_array/1, prepend/2, append/2, concat_bit_arrays/1, to_bit_array/1, byte_size/1]). --export_type([bytes_builder/0]). - --opaque bytes_builder() :: {bytes, bitstring()} | - {text, gleam@string_builder:string_builder()} | - {many, list(bytes_builder())}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bytes_builder.gleam", 72). --spec append_builder(bytes_builder(), bytes_builder()) -> bytes_builder(). -append_builder(First, Second) -> - gleam_stdlib:iodata_append(First, Second). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bytes_builder.gleam", 60). --spec prepend_builder(bytes_builder(), bytes_builder()) -> bytes_builder(). -prepend_builder(Second, First) -> - gleam_stdlib:iodata_append(First, Second). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bytes_builder.gleam", 111). --spec concat(list(bytes_builder())) -> bytes_builder(). -concat(Builders) -> - gleam_stdlib:identity(Builders). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bytes_builder.gleam", 36). --spec new() -> bytes_builder(). -new() -> - gleam_stdlib:identity([]). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bytes_builder.gleam", 132). --spec from_string(binary()) -> bytes_builder(). -from_string(String) -> - gleam_stdlib:wrap_list(String). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bytes_builder.gleam", 87). --spec prepend_string(bytes_builder(), binary()) -> bytes_builder(). -prepend_string(Second, First) -> - gleam_stdlib:iodata_append(gleam_stdlib:wrap_list(First), Second). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bytes_builder.gleam", 99). --spec append_string(bytes_builder(), binary()) -> bytes_builder(). -append_string(First, Second) -> - gleam_stdlib:iodata_append(First, gleam_stdlib:wrap_list(Second)). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bytes_builder.gleam", 142). --spec from_string_builder(gleam@string_builder:string_builder()) -> bytes_builder(). -from_string_builder(Builder) -> - gleam_stdlib:wrap_list(Builder). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bytes_builder.gleam", 151). --spec from_bit_array(bitstring()) -> bytes_builder(). -from_bit_array(Bits) -> - gleam_stdlib:wrap_list(Bits). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bytes_builder.gleam", 44). --spec prepend(bytes_builder(), bitstring()) -> bytes_builder(). -prepend(Second, First) -> - gleam_stdlib:iodata_append(gleam_stdlib:wrap_list(First), Second). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bytes_builder.gleam", 52). --spec append(bytes_builder(), bitstring()) -> bytes_builder(). -append(First, Second) -> - gleam_stdlib:iodata_append(First, gleam_stdlib:wrap_list(Second)). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bytes_builder.gleam", 120). --spec concat_bit_arrays(list(bitstring())) -> bytes_builder(). -concat_bit_arrays(Bits) -> - gleam_stdlib:identity(Bits). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bytes_builder.gleam", 170). --spec to_list(list(list(bytes_builder())), list(bitstring())) -> list(bitstring()). -to_list(Stack, Acc) -> - case Stack of - [] -> - Acc; - - [[] | Remaining_stack] -> - to_list(Remaining_stack, Acc); - - [[{bytes, Bits} | Rest] | Remaining_stack@1] -> - to_list([Rest | Remaining_stack@1], [Bits | Acc]); - - [[{text, Builder} | Rest@1] | Remaining_stack@2] -> - Bits@1 = gleam_stdlib:identity( - gleam@string_builder:to_string(Builder) - ), - to_list([Rest@1 | Remaining_stack@2], [Bits@1 | Acc]); - - [[{many, Builders} | Rest@2] | Remaining_stack@3] -> - to_list([Builders, Rest@2 | Remaining_stack@3], Acc) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bytes_builder.gleam", 163). --spec to_bit_array(bytes_builder()) -> bitstring(). -to_bit_array(Builder) -> - erlang:list_to_bitstring(Builder). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bytes_builder.gleam", 197). --spec byte_size(bytes_builder()) -> integer(). -byte_size(Builder) -> - erlang:iolist_size(Builder). diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@dict.cache b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@dict.cache deleted file mode 100644 index a76bcd70e6e..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@dict.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@dict.cache_meta b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@dict.cache_meta deleted file mode 100644 index 24d66986cea..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@dict.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@dict.erl b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@dict.erl deleted file mode 100644 index 746afb7e1a8..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@dict.erl +++ /dev/null @@ -1,224 +0,0 @@ --module(gleam@dict). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([size/1, to_list/1, new/0, is_empty/1, get/2, has_key/2, insert/3, from_list/1, keys/1, values/1, take/2, merge/2, delete/2, drop/2, upsert/3, fold/3, map_values/2, filter/2, each/2, combine/3]). --export_type([dict/2]). - --type dict(KM, KN) :: any() | {gleam_phantom, KM, KN}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dict.gleam", 36). --spec size(dict(any(), any())) -> integer(). -size(Dict) -> - maps:size(Dict). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dict.gleam", 80). --spec to_list(dict(KW, KX)) -> list({KW, KX}). -to_list(Dict) -> - maps:to_list(Dict). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dict.gleam", 127). --spec new() -> dict(any(), any()). -new() -> - maps:new(). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dict.gleam", 52). --spec is_empty(dict(any(), any())) -> boolean(). -is_empty(Dict) -> - Dict =:= new(). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dict.gleam", 152). --spec get(dict(MD, ME), MD) -> {ok, ME} | {error, nil}. -get(From, Get) -> - gleam_stdlib:map_get(From, Get). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dict.gleam", 116). --spec has_key(dict(LN, any()), LN) -> boolean(). -has_key(Dict, Key) -> - maps:is_key(Key, Dict). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dict.gleam", 177). --spec insert(dict(MP, MQ), MP, MQ) -> dict(MP, MQ). -insert(Dict, Key, Value) -> - maps:put(Key, Value, Dict). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dict.gleam", 92). --spec fold_list_of_pair(list({LG, LH}), dict(LG, LH)) -> dict(LG, LH). -fold_list_of_pair(List, Initial) -> - case List of - [] -> - Initial; - - [X | Rest] -> - fold_list_of_pair( - Rest, - insert(Initial, erlang:element(1, X), erlang:element(2, X)) - ) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dict.gleam", 88). --spec from_list(list({LB, LC})) -> dict(LB, LC). -from_list(List) -> - maps:from_list(List). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dict.gleam", 229). --spec reverse_and_concat(list(NZ), list(NZ)) -> list(NZ). -reverse_and_concat(Remaining, Accumulator) -> - case Remaining of - [] -> - Accumulator; - - [Item | Rest] -> - reverse_and_concat(Rest, [Item | Accumulator]) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dict.gleam", 236). --spec do_keys_acc(list({OD, any()}), list(OD)) -> list(OD). -do_keys_acc(List, Acc) -> - case List of - [] -> - reverse_and_concat(Acc, []); - - [First | Rest] -> - do_keys_acc(Rest, [erlang:element(1, First) | Acc]) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dict.gleam", 219). --spec keys(dict(NP, any())) -> list(NP). -keys(Dict) -> - maps:keys(Dict). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dict.gleam", 266). --spec do_values_acc(list({any(), OT}), list(OT)) -> list(OT). -do_values_acc(List, Acc) -> - case List of - [] -> - reverse_and_concat(Acc, []); - - [First | Rest] -> - do_values_acc(Rest, [erlang:element(2, First) | Acc]) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dict.gleam", 256). --spec values(dict(any(), OJ)) -> list(OJ). -values(Dict) -> - maps:values(Dict). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dict.gleam", 335). --spec insert_taken(dict(PX, PY), list(PX), dict(PX, PY)) -> dict(PX, PY). -insert_taken(Dict, Desired_keys, Acc) -> - Insert = fun(Taken, Key) -> case get(Dict, Key) of - {ok, Value} -> - insert(Taken, Key, Value); - - _ -> - Taken - end end, - case Desired_keys of - [] -> - Acc; - - [First | Rest] -> - insert_taken(Dict, Rest, Insert(Acc, First)) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dict.gleam", 326). --spec take(dict(PJ, PK), list(PJ)) -> dict(PJ, PK). -take(Dict, Desired_keys) -> - maps:with(Desired_keys, Dict). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dict.gleam", 377). --spec insert_pair(dict(QW, QX), {QW, QX}) -> dict(QW, QX). -insert_pair(Dict, Pair) -> - insert(Dict, erlang:element(1, Pair), erlang:element(2, Pair)). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dict.gleam", 381). --spec fold_inserts(list({RC, RD}), dict(RC, RD)) -> dict(RC, RD). -fold_inserts(New_entries, Dict) -> - case New_entries of - [] -> - Dict; - - [First | Rest] -> - fold_inserts(Rest, insert_pair(Dict, First)) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dict.gleam", 366). --spec merge(dict(QG, QH), dict(QG, QH)) -> dict(QG, QH). -merge(Dict, New_entries) -> - maps:merge(Dict, New_entries). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dict.gleam", 403). --spec delete(dict(RJ, RK), RJ) -> dict(RJ, RK). -delete(Dict, Key) -> - maps:remove(Key, Dict). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dict.gleam", 431). --spec drop(dict(RV, RW), list(RV)) -> dict(RV, RW). -drop(Dict, Disallowed_keys) -> - case Disallowed_keys of - [] -> - Dict; - - [First | Rest] -> - drop(delete(Dict, First), Rest) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dict.gleam", 461). --spec upsert(dict(SC, SD), SC, fun((gleam@option:option(SD)) -> SD)) -> dict(SC, SD). -upsert(Dict, Key, Fun) -> - _pipe = Dict, - _pipe@1 = get(_pipe, Key), - _pipe@2 = gleam@option:from_result(_pipe@1), - _pipe@3 = Fun(_pipe@2), - insert(Dict, Key, _pipe@3). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dict.gleam", 473). --spec do_fold(list({SJ, SK}), SM, fun((SM, SJ, SK) -> SM)) -> SM. -do_fold(List, Initial, Fun) -> - case List of - [] -> - Initial; - - [{K, V} | Rest] -> - do_fold(Rest, Fun(Initial, K, V), Fun) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dict.gleam", 505). --spec fold(dict(SN, SO), SR, fun((SR, SN, SO) -> SR)) -> SR. -fold(Dict, Initial, Fun) -> - _pipe = Dict, - _pipe@1 = maps:to_list(_pipe), - do_fold(_pipe@1, Initial, Fun). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dict.gleam", 196). --spec map_values(dict(NB, NC), fun((NB, NC) -> NF)) -> dict(NB, NF). -map_values(Dict, Fun) -> - maps:map(Fun, Dict). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dict.gleam", 290). --spec filter(dict(OX, OY), fun((OX, OY) -> boolean())) -> dict(OX, OY). -filter(Dict, Predicate) -> - maps:filter(Predicate, Dict). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dict.gleam", 537). --spec each(dict(SS, ST), fun((SS, ST) -> any())) -> nil. -each(Dict, Fun) -> - fold( - Dict, - nil, - fun(Nil, K, V) -> - Fun(K, V), - Nil - end - ). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dict.gleam", 558). --spec combine(dict(SX, SY), dict(SX, SY), fun((SY, SY) -> SY)) -> dict(SX, SY). -combine(Dict, Other, Fun) -> - fold(Dict, Other, fun(Acc, Key, Value) -> case get(Acc, Key) of - {ok, Other_value} -> - insert(Acc, Key, Fun(Value, Other_value)); - - {error, _} -> - insert(Acc, Key, Value) - end end). diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@dynamic.cache b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@dynamic.cache deleted file mode 100644 index 59ee24a9e9f..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@dynamic.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@dynamic.cache_meta b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@dynamic.cache_meta deleted file mode 100644 index 7ff3f002393..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@dynamic.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@dynamic.erl b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@dynamic.erl deleted file mode 100644 index a3d3a9799b6..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@dynamic.erl +++ /dev/null @@ -1,832 +0,0 @@ --module(gleam@dynamic). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([from/1, dynamic/1, bit_array/1, classify/1, int/1, float/1, bool/1, shallow_list/1, optional/1, any/1, decode1/2, result/2, list/1, string/1, field/2, optional_field/2, element/2, tuple2/2, tuple3/3, tuple4/4, tuple5/5, tuple6/6, dict/2, decode2/3, decode3/4, decode4/5, decode5/6, decode6/7, decode7/8, decode8/9, decode9/10]). --export_type([dynamic_/0, decode_error/0, unknown_tuple/0]). - --type dynamic_() :: any(). - --type decode_error() :: {decode_error, binary(), binary(), list(binary())}. - --type unknown_tuple() :: any(). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 31). --spec from(any()) -> dynamic_(). -from(A) -> - gleam_stdlib:identity(A). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 39). --spec dynamic(dynamic_()) -> {ok, dynamic_()} | {error, list(decode_error())}. -dynamic(Value) -> - {ok, Value}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 60). --spec bit_array(dynamic_()) -> {ok, bitstring()} | {error, list(decode_error())}. -bit_array(Data) -> - gleam_stdlib:decode_bit_array(Data). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 107). --spec put_expected(decode_error(), binary()) -> decode_error(). -put_expected(Error, Expected) -> - erlang:setelement(2, Error, Expected). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 118). --spec classify(dynamic_()) -> binary(). -classify(Data) -> - gleam_stdlib:classify_dynamic(Data). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 141). --spec int(dynamic_()) -> {ok, integer()} | {error, list(decode_error())}. -int(Data) -> - gleam_stdlib:decode_int(Data). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 164). --spec float(dynamic_()) -> {ok, float()} | {error, list(decode_error())}. -float(Data) -> - gleam_stdlib:decode_float(Data). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 187). --spec bool(dynamic_()) -> {ok, boolean()} | {error, list(decode_error())}. -bool(Data) -> - gleam_stdlib:decode_bool(Data). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 213). --spec shallow_list(dynamic_()) -> {ok, list(dynamic_())} | - {error, list(decode_error())}. -shallow_list(Value) -> - gleam_stdlib:decode_list(Value). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 356). --spec optional(fun((dynamic_()) -> {ok, CJC} | {error, list(decode_error())})) -> fun((dynamic_()) -> {ok, - gleam@option:option(CJC)} | - {error, list(decode_error())}). -optional(Decode) -> - fun(Value) -> gleam_stdlib:decode_option(Value, Decode) end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 491). --spec at_least_decode_tuple_error(integer(), dynamic_()) -> {ok, any()} | - {error, list(decode_error())}. -at_least_decode_tuple_error(Size, Data) -> - S = case Size of - 1 -> - <<""/utf8>>; - - _ -> - <<"s"/utf8>> - end, - Error = begin - _pipe = [<<"Tuple of at least "/utf8>>, - gleam@int:to_string(Size), - <<" element"/utf8>>, - S], - _pipe@1 = gleam@string_builder:from_strings(_pipe), - _pipe@2 = gleam@string_builder:to_string(_pipe@1), - {decode_error, _pipe@2, classify(Data), []} - end, - {error, [Error]}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 1021). --spec any(list(fun((dynamic_()) -> {ok, CNC} | {error, list(decode_error())}))) -> fun((dynamic_()) -> {ok, - CNC} | - {error, list(decode_error())}). -any(Decoders) -> - fun(Data) -> case Decoders of - [] -> - {error, - [{decode_error, <<"another type"/utf8>>, classify(Data), []}]}; - - [Decoder | Decoders@1] -> - case Decoder(Data) of - {ok, Decoded} -> - {ok, Decoded}; - - {error, _} -> - (any(Decoders@1))(Data) - end - end end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 1517). --spec all_errors({ok, any()} | {error, list(decode_error())}) -> list(decode_error()). -all_errors(Result) -> - case Result of - {ok, _} -> - []; - - {error, Errors} -> - Errors - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 1054). --spec decode1( - fun((CNG) -> CNH), - fun((dynamic_()) -> {ok, CNG} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, CNH} | {error, list(decode_error())}). -decode1(Constructor, T1) -> - fun(Value) -> case T1(Value) of - {ok, A} -> - {ok, Constructor(A)}; - - A@1 -> - {error, all_errors(A@1)} - end end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 563). --spec push_path(decode_error(), any()) -> decode_error(). -push_path(Error, Name) -> - Name@1 = gleam_stdlib:identity(Name), - Decoder = any( - [fun string/1, - fun(X) -> gleam@result:map(int(X), fun gleam@int:to_string/1) end] - ), - Name@3 = case Decoder(Name@1) of - {ok, Name@2} -> - Name@2; - - {error, _} -> - _pipe = [<<"<"/utf8>>, classify(Name@1), <<">"/utf8>>], - _pipe@1 = gleam@string_builder:from_strings(_pipe), - gleam@string_builder:to_string(_pipe@1) - end, - erlang:setelement(4, Error, [Name@3 | erlang:element(4, Error)]). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 248). --spec result( - fun((dynamic_()) -> {ok, CIQ} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CIS} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, {ok, CIQ} | {error, CIS}} | - {error, list(decode_error())}). -result(Decode_ok, Decode_error) -> - fun(Value) -> - gleam@result:'try'( - gleam_stdlib:decode_result(Value), - fun(Inner_result) -> case Inner_result of - {ok, Raw} -> - gleam@result:'try'( - begin - _pipe = Decode_ok(Raw), - map_errors( - _pipe, - fun(_capture) -> - push_path(_capture, <<"ok"/utf8>>) - end - ) - end, - fun(Value@1) -> {ok, {ok, Value@1}} end - ); - - {error, Raw@1} -> - gleam@result:'try'( - begin - _pipe@1 = Decode_error(Raw@1), - map_errors( - _pipe@1, - fun(_capture@1) -> - push_path(_capture@1, <<"error"/utf8>>) - end - ) - end, - fun(Value@2) -> {ok, {error, Value@2}} end - ) - end end - ) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 301). --spec list(fun((dynamic_()) -> {ok, CIX} | {error, list(decode_error())})) -> fun((dynamic_()) -> {ok, - list(CIX)} | - {error, list(decode_error())}). -list(Decoder_type) -> - fun(Dynamic) -> - gleam@result:'try'(shallow_list(Dynamic), fun(List) -> _pipe = List, - _pipe@1 = gleam@list:try_map(_pipe, Decoder_type), - map_errors( - _pipe@1, - fun(_capture) -> push_path(_capture, <<"*"/utf8>>) end - ) end) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 87). --spec map_errors( - {ok, CHL} | {error, list(decode_error())}, - fun((decode_error()) -> decode_error()) -) -> {ok, CHL} | {error, list(decode_error())}. -map_errors(Result, F) -> - gleam@result:map_error( - Result, - fun(_capture) -> gleam@list:map(_capture, F) end - ). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 95). --spec decode_string(dynamic_()) -> {ok, binary()} | - {error, list(decode_error())}. -decode_string(Data) -> - _pipe = bit_array(Data), - _pipe@1 = map_errors( - _pipe, - fun(_capture) -> put_expected(_capture, <<"String"/utf8>>) end - ), - gleam@result:'try'( - _pipe@1, - fun(Raw) -> case gleam@bit_array:to_string(Raw) of - {ok, String} -> - {ok, String}; - - {error, nil} -> - {error, - [{decode_error, - <<"String"/utf8>>, - <<"BitArray"/utf8>>, - []}]} - end end - ). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 83). --spec string(dynamic_()) -> {ok, binary()} | {error, list(decode_error())}. -string(Data) -> - decode_string(Data). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 385). --spec field( - any(), - fun((dynamic_()) -> {ok, CJM} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, CJM} | {error, list(decode_error())}). -field(Name, Inner_type) -> - fun(Value) -> - Missing_field_error = {decode_error, - <<"field"/utf8>>, - <<"nothing"/utf8>>, - []}, - gleam@result:'try'( - gleam_stdlib:decode_field(Value, Name), - fun(Maybe_inner) -> _pipe = Maybe_inner, - _pipe@1 = gleam@option:to_result(_pipe, [Missing_field_error]), - _pipe@2 = gleam@result:'try'(_pipe@1, Inner_type), - map_errors( - _pipe@2, - fun(_capture) -> push_path(_capture, Name) end - ) end - ) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 427). --spec optional_field( - any(), - fun((dynamic_()) -> {ok, CJQ} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, gleam@option:option(CJQ)} | - {error, list(decode_error())}). -optional_field(Name, Inner_type) -> - fun(Value) -> - gleam@result:'try'( - gleam_stdlib:decode_field(Value, Name), - fun(Maybe_inner) -> case Maybe_inner of - none -> - {ok, none}; - - {some, Dynamic_inner} -> - _pipe = Inner_type(Dynamic_inner), - _pipe@1 = gleam@result:map( - _pipe, - fun(Field@0) -> {some, Field@0} end - ), - map_errors( - _pipe@1, - fun(_capture) -> push_path(_capture, Name) end - ) - end end - ) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 470). --spec element( - integer(), - fun((dynamic_()) -> {ok, CJY} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, CJY} | {error, list(decode_error())}). -element(Index, Inner_type) -> - fun(Data) -> - gleam@result:'try'( - gleam_stdlib:decode_tuple(Data), - fun(Tuple) -> - Size = gleam_stdlib:size_of_tuple(Tuple), - gleam@result:'try'(case Index >= 0 of - true -> - case Index < Size of - true -> - gleam_stdlib:tuple_get(Tuple, Index); - - false -> - at_least_decode_tuple_error(Index + 1, Data) - end; - - false -> - case gleam@int:absolute_value(Index) =< Size of - true -> - gleam_stdlib:tuple_get(Tuple, Size + Index); - - false -> - at_least_decode_tuple_error( - gleam@int:absolute_value(Index), - Data - ) - end - end, fun(Data@1) -> _pipe = Inner_type(Data@1), - map_errors( - _pipe, - fun(_capture) -> push_path(_capture, Index) end - ) end) - end - ) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 553). --spec tuple_errors({ok, any()} | {error, list(decode_error())}, binary()) -> list(decode_error()). -tuple_errors(Result, Name) -> - case Result of - {ok, _} -> - []; - - {error, Errors} -> - gleam@list:map( - Errors, - fun(_capture) -> push_path(_capture, Name) end - ) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 629). --spec tuple2( - fun((dynamic_()) -> {ok, CKY} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CLA} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, {CKY, CLA}} | {error, list(decode_error())}). -tuple2(Decode1, Decode2) -> - fun(Value) -> - gleam@result:'try'( - gleam_stdlib:decode_tuple2(Value), - fun(_use0) -> - {A, B} = _use0, - case {Decode1(A), Decode2(B)} of - {{ok, A@1}, {ok, B@1}} -> - {ok, {A@1, B@1}}; - - {A@2, B@2} -> - _pipe = tuple_errors(A@2, <<"0"/utf8>>), - _pipe@1 = lists:append( - _pipe, - tuple_errors(B@2, <<"1"/utf8>>) - ), - {error, _pipe@1} - end - end - ) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 698). --spec tuple3( - fun((dynamic_()) -> {ok, CLD} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CLF} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CLH} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, {CLD, CLF, CLH}} | {error, list(decode_error())}). -tuple3(Decode1, Decode2, Decode3) -> - fun(Value) -> - gleam@result:'try'( - gleam_stdlib:decode_tuple3(Value), - fun(_use0) -> - {A, B, C} = _use0, - case {Decode1(A), Decode2(B), Decode3(C)} of - {{ok, A@1}, {ok, B@1}, {ok, C@1}} -> - {ok, {A@1, B@1, C@1}}; - - {A@2, B@2, C@2} -> - _pipe = tuple_errors(A@2, <<"0"/utf8>>), - _pipe@1 = lists:append( - _pipe, - tuple_errors(B@2, <<"1"/utf8>>) - ), - _pipe@2 = lists:append( - _pipe@1, - tuple_errors(C@2, <<"2"/utf8>>) - ), - {error, _pipe@2} - end - end - ) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 769). --spec tuple4( - fun((dynamic_()) -> {ok, CLK} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CLM} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CLO} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CLQ} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, {CLK, CLM, CLO, CLQ}} | - {error, list(decode_error())}). -tuple4(Decode1, Decode2, Decode3, Decode4) -> - fun(Value) -> - gleam@result:'try'( - gleam_stdlib:decode_tuple4(Value), - fun(_use0) -> - {A, B, C, D} = _use0, - case {Decode1(A), Decode2(B), Decode3(C), Decode4(D)} of - {{ok, A@1}, {ok, B@1}, {ok, C@1}, {ok, D@1}} -> - {ok, {A@1, B@1, C@1, D@1}}; - - {A@2, B@2, C@2, D@2} -> - _pipe = tuple_errors(A@2, <<"0"/utf8>>), - _pipe@1 = lists:append( - _pipe, - tuple_errors(B@2, <<"1"/utf8>>) - ), - _pipe@2 = lists:append( - _pipe@1, - tuple_errors(C@2, <<"2"/utf8>>) - ), - _pipe@3 = lists:append( - _pipe@2, - tuple_errors(D@2, <<"3"/utf8>>) - ), - {error, _pipe@3} - end - end - ) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 842). --spec tuple5( - fun((dynamic_()) -> {ok, CLT} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CLV} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CLX} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CLZ} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CMB} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, {CLT, CLV, CLX, CLZ, CMB}} | - {error, list(decode_error())}). -tuple5(Decode1, Decode2, Decode3, Decode4, Decode5) -> - fun(Value) -> - gleam@result:'try'( - gleam_stdlib:decode_tuple5(Value), - fun(_use0) -> - {A, B, C, D, E} = _use0, - case {Decode1(A), - Decode2(B), - Decode3(C), - Decode4(D), - Decode5(E)} of - {{ok, A@1}, {ok, B@1}, {ok, C@1}, {ok, D@1}, {ok, E@1}} -> - {ok, {A@1, B@1, C@1, D@1, E@1}}; - - {A@2, B@2, C@2, D@2, E@2} -> - _pipe = tuple_errors(A@2, <<"0"/utf8>>), - _pipe@1 = lists:append( - _pipe, - tuple_errors(B@2, <<"1"/utf8>>) - ), - _pipe@2 = lists:append( - _pipe@1, - tuple_errors(C@2, <<"2"/utf8>>) - ), - _pipe@3 = lists:append( - _pipe@2, - tuple_errors(D@2, <<"3"/utf8>>) - ), - _pipe@4 = lists:append( - _pipe@3, - tuple_errors(E@2, <<"4"/utf8>>) - ), - {error, _pipe@4} - end - end - ) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 917). --spec tuple6( - fun((dynamic_()) -> {ok, CME} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CMG} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CMI} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CMK} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CMM} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CMO} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, {CME, CMG, CMI, CMK, CMM, CMO}} | - {error, list(decode_error())}). -tuple6(Decode1, Decode2, Decode3, Decode4, Decode5, Decode6) -> - fun(Value) -> - gleam@result:'try'( - gleam_stdlib:decode_tuple6(Value), - fun(_use0) -> - {A, B, C, D, E, F} = _use0, - case {Decode1(A), - Decode2(B), - Decode3(C), - Decode4(D), - Decode5(E), - Decode6(F)} of - {{ok, A@1}, - {ok, B@1}, - {ok, C@1}, - {ok, D@1}, - {ok, E@1}, - {ok, F@1}} -> - {ok, {A@1, B@1, C@1, D@1, E@1, F@1}}; - - {A@2, B@2, C@2, D@2, E@2, F@2} -> - _pipe = tuple_errors(A@2, <<"0"/utf8>>), - _pipe@1 = lists:append( - _pipe, - tuple_errors(B@2, <<"1"/utf8>>) - ), - _pipe@2 = lists:append( - _pipe@1, - tuple_errors(C@2, <<"2"/utf8>>) - ), - _pipe@3 = lists:append( - _pipe@2, - tuple_errors(D@2, <<"3"/utf8>>) - ), - _pipe@4 = lists:append( - _pipe@3, - tuple_errors(E@2, <<"4"/utf8>>) - ), - _pipe@5 = lists:append( - _pipe@4, - tuple_errors(F@2, <<"5"/utf8>>) - ), - {error, _pipe@5} - end - end - ) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 968). --spec dict( - fun((dynamic_()) -> {ok, CMR} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CMT} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, gleam@dict:dict(CMR, CMT)} | - {error, list(decode_error())}). -dict(Key_type, Value_type) -> - fun(Value) -> - gleam@result:'try'( - gleam_stdlib:decode_map(Value), - fun(Map) -> - gleam@result:'try'( - begin - _pipe = Map, - _pipe@1 = maps:to_list(_pipe), - gleam@list:try_map( - _pipe@1, - fun(Pair) -> - {K, V} = Pair, - gleam@result:'try'( - begin - _pipe@2 = Key_type(K), - map_errors( - _pipe@2, - fun(_capture) -> - push_path( - _capture, - <<"keys"/utf8>> - ) - end - ) - end, - fun(K@1) -> - gleam@result:'try'( - begin - _pipe@3 = Value_type(V), - map_errors( - _pipe@3, - fun(_capture@1) -> - push_path( - _capture@1, - <<"values"/utf8>> - ) - end - ) - end, - fun(V@1) -> {ok, {K@1, V@1}} end - ) - end - ) - end - ) - end, - fun(Pairs) -> {ok, maps:from_list(Pairs)} end - ) - end - ) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 1082). --spec decode2( - fun((CNK, CNL) -> CNM), - fun((dynamic_()) -> {ok, CNK} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CNL} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, CNM} | {error, list(decode_error())}). -decode2(Constructor, T1, T2) -> - fun(Value) -> case {T1(Value), T2(Value)} of - {{ok, A}, {ok, B}} -> - {ok, Constructor(A, B)}; - - {A@1, B@1} -> - {error, gleam@list:flatten([all_errors(A@1), all_errors(B@1)])} - end end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 1114). --spec decode3( - fun((CNQ, CNR, CNS) -> CNT), - fun((dynamic_()) -> {ok, CNQ} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CNR} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CNS} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, CNT} | {error, list(decode_error())}). -decode3(Constructor, T1, T2, T3) -> - fun(Value) -> case {T1(Value), T2(Value), T3(Value)} of - {{ok, A}, {ok, B}, {ok, C}} -> - {ok, Constructor(A, B, C)}; - - {A@1, B@1, C@1} -> - {error, - gleam@list:flatten( - [all_errors(A@1), all_errors(B@1), all_errors(C@1)] - )} - end end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 1160). --spec decode4( - fun((CNY, CNZ, COA, COB) -> COC), - fun((dynamic_()) -> {ok, CNY} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CNZ} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, COA} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, COB} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, COC} | {error, list(decode_error())}). -decode4(Constructor, T1, T2, T3, T4) -> - fun(X) -> case {T1(X), T2(X), T3(X), T4(X)} of - {{ok, A}, {ok, B}, {ok, C}, {ok, D}} -> - {ok, Constructor(A, B, C, D)}; - - {A@1, B@1, C@1, D@1} -> - {error, - gleam@list:flatten( - [all_errors(A@1), - all_errors(B@1), - all_errors(C@1), - all_errors(D@1)] - )} - end end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 1216). --spec decode5( - fun((COI, COJ, COK, COL, COM) -> CON), - fun((dynamic_()) -> {ok, COI} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, COJ} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, COK} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, COL} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, COM} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, CON} | {error, list(decode_error())}). -decode5(Constructor, T1, T2, T3, T4, T5) -> - fun(X) -> case {T1(X), T2(X), T3(X), T4(X), T5(X)} of - {{ok, A}, {ok, B}, {ok, C}, {ok, D}, {ok, E}} -> - {ok, Constructor(A, B, C, D, E)}; - - {A@1, B@1, C@1, D@1, E@1} -> - {error, - gleam@list:flatten( - [all_errors(A@1), - all_errors(B@1), - all_errors(C@1), - all_errors(D@1), - all_errors(E@1)] - )} - end end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 1276). --spec decode6( - fun((COU, COV, COW, COX, COY, COZ) -> CPA), - fun((dynamic_()) -> {ok, COU} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, COV} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, COW} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, COX} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, COY} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, COZ} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, CPA} | {error, list(decode_error())}). -decode6(Constructor, T1, T2, T3, T4, T5, T6) -> - fun(X) -> case {T1(X), T2(X), T3(X), T4(X), T5(X), T6(X)} of - {{ok, A}, {ok, B}, {ok, C}, {ok, D}, {ok, E}, {ok, F}} -> - {ok, Constructor(A, B, C, D, E, F)}; - - {A@1, B@1, C@1, D@1, E@1, F@1} -> - {error, - gleam@list:flatten( - [all_errors(A@1), - all_errors(B@1), - all_errors(C@1), - all_errors(D@1), - all_errors(E@1), - all_errors(F@1)] - )} - end end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 1341). --spec decode7( - fun((CPI, CPJ, CPK, CPL, CPM, CPN, CPO) -> CPP), - fun((dynamic_()) -> {ok, CPI} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CPJ} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CPK} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CPL} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CPM} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CPN} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CPO} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, CPP} | {error, list(decode_error())}). -decode7(Constructor, T1, T2, T3, T4, T5, T6, T7) -> - fun(X) -> case {T1(X), T2(X), T3(X), T4(X), T5(X), T6(X), T7(X)} of - {{ok, A}, {ok, B}, {ok, C}, {ok, D}, {ok, E}, {ok, F}, {ok, G}} -> - {ok, Constructor(A, B, C, D, E, F, G)}; - - {A@1, B@1, C@1, D@1, E@1, F@1, G@1} -> - {error, - gleam@list:flatten( - [all_errors(A@1), - all_errors(B@1), - all_errors(C@1), - all_errors(D@1), - all_errors(E@1), - all_errors(F@1), - all_errors(G@1)] - )} - end end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 1410). --spec decode8( - fun((CPY, CPZ, CQA, CQB, CQC, CQD, CQE, CQF) -> CQG), - fun((dynamic_()) -> {ok, CPY} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CPZ} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQA} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQB} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQC} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQD} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQE} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQF} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, CQG} | {error, list(decode_error())}). -decode8(Constructor, T1, T2, T3, T4, T5, T6, T7, T8) -> - fun(X) -> case {T1(X), T2(X), T3(X), T4(X), T5(X), T6(X), T7(X), T8(X)} of - {{ok, A}, - {ok, B}, - {ok, C}, - {ok, D}, - {ok, E}, - {ok, F}, - {ok, G}, - {ok, H}} -> - {ok, Constructor(A, B, C, D, E, F, G, H)}; - - {A@1, B@1, C@1, D@1, E@1, F@1, G@1, H@1} -> - {error, - gleam@list:flatten( - [all_errors(A@1), - all_errors(B@1), - all_errors(C@1), - all_errors(D@1), - all_errors(E@1), - all_errors(F@1), - all_errors(G@1), - all_errors(H@1)] - )} - end end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam", 1483). --spec decode9( - fun((CQQ, CQR, CQS, CQT, CQU, CQV, CQW, CQX, CQY) -> CQZ), - fun((dynamic_()) -> {ok, CQQ} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQR} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQS} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQT} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQU} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQV} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQW} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQX} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQY} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, CQZ} | {error, list(decode_error())}). -decode9(Constructor, T1, T2, T3, T4, T5, T6, T7, T8, T9) -> - fun(X) -> - case {T1(X), T2(X), T3(X), T4(X), T5(X), T6(X), T7(X), T8(X), T9(X)} of - {{ok, A}, - {ok, B}, - {ok, C}, - {ok, D}, - {ok, E}, - {ok, F}, - {ok, G}, - {ok, H}, - {ok, I}} -> - {ok, Constructor(A, B, C, D, E, F, G, H, I)}; - - {A@1, B@1, C@1, D@1, E@1, F@1, G@1, H@1, I@1} -> - {error, - gleam@list:flatten( - [all_errors(A@1), - all_errors(B@1), - all_errors(C@1), - all_errors(D@1), - all_errors(E@1), - all_errors(F@1), - all_errors(G@1), - all_errors(H@1), - all_errors(I@1)] - )} - end - end. diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@float.cache b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@float.cache deleted file mode 100644 index 4fdb5115204..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@float.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@float.cache_meta b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@float.cache_meta deleted file mode 100644 index 8e748265eb2..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@float.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@float.erl b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@float.erl deleted file mode 100644 index d055cc0f325..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@float.erl +++ /dev/null @@ -1,231 +0,0 @@ --module(gleam@float). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([parse/1, to_string/1, compare/2, min/2, max/2, clamp/3, ceiling/1, floor/1, truncate/1, absolute_value/1, loosely_compare/3, loosely_equals/3, power/2, square_root/1, negate/1, round/1, to_precision/2, sum/1, product/1, random/0, modulo/2, divide/2, add/2, multiply/2, subtract/2]). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/float.gleam", 32). --spec parse(binary()) -> {ok, float()} | {error, nil}. -parse(String) -> - gleam_stdlib:parse_float(String). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/float.gleam", 49). --spec to_string(float()) -> binary(). -to_string(X) -> - gleam_stdlib:float_to_string(X). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/float.gleam", 86). --spec compare(float(), float()) -> gleam@order:order(). -compare(A, B) -> - case A =:= B of - true -> - eq; - - false -> - case A < B of - true -> - lt; - - false -> - gt - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/float.gleam", 167). --spec min(float(), float()) -> float(). -min(A, B) -> - case A < B of - true -> - A; - - false -> - B - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/float.gleam", 183). --spec max(float(), float()) -> float(). -max(A, B) -> - case A > B of - true -> - A; - - false -> - B - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/float.gleam", 66). --spec clamp(float(), float(), float()) -> float(). -clamp(X, Min_bound, Max_bound) -> - _pipe = X, - _pipe@1 = min(_pipe, Max_bound), - max(_pipe@1, Min_bound). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/float.gleam", 199). --spec ceiling(float()) -> float(). -ceiling(X) -> - math:ceil(X). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/float.gleam", 216). --spec floor(float()) -> float(). -floor(X) -> - math:floor(X). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/float.gleam", 262). --spec truncate(float()) -> integer(). -truncate(X) -> - erlang:trunc(X). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/float.gleam", 310). --spec absolute_value(float()) -> float(). -absolute_value(X) -> - case X >= +0.0 of - true -> - X; - - _ -> - +0.0 - X - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/float.gleam", 116). --spec loosely_compare(float(), float(), float()) -> gleam@order:order(). -loosely_compare(A, B, Tolerance) -> - Difference = absolute_value(A - B), - case Difference =< Tolerance of - true -> - eq; - - false -> - compare(A, B) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/float.gleam", 149). --spec loosely_equals(float(), float(), float()) -> boolean(). -loosely_equals(A, B, Tolerance) -> - Difference = absolute_value(A - B), - Difference =< Tolerance. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/float.gleam", 347). --spec power(float(), float()) -> {ok, float()} | {error, nil}. -power(Base, Exponent) -> - Fractional = (ceiling(Exponent) - Exponent) > +0.0, - case ((Base < +0.0) andalso Fractional) orelse ((Base =:= +0.0) andalso (Exponent - < +0.0)) of - true -> - {error, nil}; - - false -> - {ok, math:pow(Base, Exponent)} - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/float.gleam", 379). --spec square_root(float()) -> {ok, float()} | {error, nil}. -square_root(X) -> - power(X, 0.5). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/float.gleam", 392). --spec negate(float()) -> float(). -negate(X) -> - -1.0 * X. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/float.gleam", 238). --spec round(float()) -> integer(). -round(X) -> - erlang:round(X). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/float.gleam", 287). --spec to_precision(float(), integer()) -> float(). -to_precision(X, Precision) -> - Factor = math:pow(10.0, erlang:float(- Precision)), - erlang:float(round(case Factor of - +0.0 -> +0.0; - -0.0 -> -0.0; - Gleam@denominator -> X / Gleam@denominator - end)) * Factor. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/float.gleam", 410). --spec do_sum(list(float()), float()) -> float(). -do_sum(Numbers, Initial) -> - case Numbers of - [] -> - Initial; - - [X | Rest] -> - do_sum(Rest, X + Initial) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/float.gleam", 405). --spec sum(list(float())) -> float(). -sum(Numbers) -> - _pipe = Numbers, - do_sum(_pipe, +0.0). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/float.gleam", 433). --spec do_product(list(float()), float()) -> float(). -do_product(Numbers, Initial) -> - case Numbers of - [] -> - Initial; - - [X | Rest] -> - do_product(Rest, X * Initial) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/float.gleam", 426). --spec product(list(float())) -> float(). -product(Numbers) -> - case Numbers of - [] -> - 1.0; - - _ -> - do_product(Numbers, 1.0) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/float.gleam", 455). --spec random() -> float(). -random() -> - rand:uniform(). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/float.gleam", 484). --spec modulo(float(), float()) -> {ok, float()} | {error, nil}. -modulo(Dividend, Divisor) -> - case Divisor of - +0.0 -> - {error, nil}; - - _ -> - {ok, Dividend - (floor(case Divisor of - +0.0 -> +0.0; - -0.0 -> -0.0; - Gleam@denominator -> Dividend / Gleam@denominator - end) * Divisor)} - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/float.gleam", 505). --spec divide(float(), float()) -> {ok, float()} | {error, nil}. -divide(A, B) -> - case B of - +0.0 -> - {error, nil}; - - B@1 -> - {ok, case B@1 of - +0.0 -> +0.0; - -0.0 -> -0.0; - Gleam@denominator -> A / Gleam@denominator - end} - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/float.gleam", 536). --spec add(float(), float()) -> float(). -add(A, B) -> - A + B. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/float.gleam", 564). --spec multiply(float(), float()) -> float(). -multiply(A, B) -> - A * B. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/float.gleam", 597). --spec subtract(float(), float()) -> float(). -subtract(A, B) -> - A - B. diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@function.cache b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@function.cache deleted file mode 100644 index 1a089bb20a8..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@function.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@function.cache_meta b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@function.cache_meta deleted file mode 100644 index 44e88039a8c..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@function.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@function.erl b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@function.erl deleted file mode 100644 index 950b6bd5c10..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@function.erl +++ /dev/null @@ -1,80 +0,0 @@ --module(gleam@function). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([compose/2, curry2/1, curry3/1, curry4/1, curry5/1, curry6/1, flip/1, identity/1, constant/1, tap/2, apply1/2, apply2/3, apply3/4]). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/function.gleam", 2). --spec compose(fun((DPQ) -> DPR), fun((DPR) -> DPS)) -> fun((DPQ) -> DPS). -compose(Fun1, Fun2) -> - fun(A) -> Fun2(Fun1(A)) end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/function.gleam", 7). --spec curry2(fun((DPT, DPU) -> DPV)) -> fun((DPT) -> fun((DPU) -> DPV)). -curry2(Fun) -> - fun(A) -> fun(B) -> Fun(A, B) end end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/function.gleam", 12). --spec curry3(fun((DPX, DPY, DPZ) -> DQA)) -> fun((DPX) -> fun((DPY) -> fun((DPZ) -> DQA))). -curry3(Fun) -> - fun(A) -> fun(B) -> fun(C) -> Fun(A, B, C) end end end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/function.gleam", 17). --spec curry4(fun((DQC, DQD, DQE, DQF) -> DQG)) -> fun((DQC) -> fun((DQD) -> fun((DQE) -> fun((DQF) -> DQG)))). -curry4(Fun) -> - fun(A) -> fun(B) -> fun(C) -> fun(D) -> Fun(A, B, C, D) end end end end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/function.gleam", 22). --spec curry5(fun((DQI, DQJ, DQK, DQL, DQM) -> DQN)) -> fun((DQI) -> fun((DQJ) -> fun((DQK) -> fun((DQL) -> fun((DQM) -> DQN))))). -curry5(Fun) -> - fun(A) -> - fun(B) -> - fun(C) -> fun(D) -> fun(E) -> Fun(A, B, C, D, E) end end end - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/function.gleam", 27). --spec curry6(fun((DQP, DQQ, DQR, DQS, DQT, DQU) -> DQV)) -> fun((DQP) -> fun((DQQ) -> fun((DQR) -> fun((DQS) -> fun((DQT) -> fun((DQU) -> DQV)))))). -curry6(Fun) -> - fun(A) -> - fun(B) -> - fun(C) -> - fun(D) -> fun(E) -> fun(F) -> Fun(A, B, C, D, E, F) end end end - end - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/function.gleam", 36). --spec flip(fun((DQX, DQY) -> DQZ)) -> fun((DQY, DQX) -> DQZ). -flip(Fun) -> - fun(B, A) -> Fun(A, B) end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/function.gleam", 42). --spec identity(DRA) -> DRA. -identity(X) -> - X. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/function.gleam", 47). --spec constant(DRB) -> fun((any()) -> DRB). -constant(Value) -> - fun(_) -> Value end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/function.gleam", 56). --spec tap(DRD, fun((DRD) -> any())) -> DRD. -tap(Arg, Effect) -> - Effect(Arg), - Arg. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/function.gleam", 62). --spec apply1(fun((DRF) -> DRG), DRF) -> DRG. -apply1(Fun, Arg1) -> - Fun(Arg1). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/function.gleam", 67). --spec apply2(fun((DRH, DRI) -> DRJ), DRH, DRI) -> DRJ. -apply2(Fun, Arg1, Arg2) -> - Fun(Arg1, Arg2). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/function.gleam", 72). --spec apply3(fun((DRK, DRL, DRM) -> DRN), DRK, DRL, DRM) -> DRN. -apply3(Fun, Arg1, Arg2, Arg3) -> - Fun(Arg1, Arg2, Arg3). diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@int.cache b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@int.cache deleted file mode 100644 index 0799a77c87a..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@int.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@int.cache_meta b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@int.cache_meta deleted file mode 100644 index 84d31d8f4b7..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@int.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@int.erl b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@int.erl deleted file mode 100644 index effa63b25c3..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@int.erl +++ /dev/null @@ -1,367 +0,0 @@ --module(gleam@int). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([absolute_value/1, parse/1, base_parse/2, to_string/1, to_base_string/2, to_base2/1, to_base8/1, to_base16/1, to_base36/1, to_float/1, power/2, square_root/1, compare/2, min/2, max/2, clamp/3, is_even/1, is_odd/1, negate/1, sum/1, product/1, digits/2, undigits/2, random/1, divide/2, remainder/2, modulo/2, floor_divide/2, add/2, multiply/2, subtract/2, bitwise_and/2, bitwise_not/1, bitwise_or/2, bitwise_exclusive_or/2, bitwise_shift_left/2, bitwise_shift_right/2]). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 30). --spec absolute_value(integer()) -> integer(). -absolute_value(X) -> - case X >= 0 of - true -> - X; - - false -> - X * -1 - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 107). --spec parse(binary()) -> {ok, integer()} | {error, nil}. -parse(String) -> - gleam_stdlib:parse_int(String). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 145). --spec base_parse(binary(), integer()) -> {ok, integer()} | {error, nil}. -base_parse(String, Base) -> - case (Base >= 2) andalso (Base =< 36) of - true -> - gleam_stdlib:int_from_base_string(String, Base); - - false -> - {error, nil} - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 165). --spec to_string(integer()) -> binary(). -to_string(X) -> - erlang:integer_to_binary(X). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 204). --spec to_base_string(integer(), integer()) -> {ok, binary()} | {error, nil}. -to_base_string(X, Base) -> - case (Base >= 2) andalso (Base =< 36) of - true -> - {ok, erlang:integer_to_binary(X, Base)}; - - false -> - {error, nil} - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 224). --spec to_base2(integer()) -> binary(). -to_base2(X) -> - erlang:integer_to_binary(X, 2). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 237). --spec to_base8(integer()) -> binary(). -to_base8(X) -> - erlang:integer_to_binary(X, 8). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 250). --spec to_base16(integer()) -> binary(). -to_base16(X) -> - erlang:integer_to_binary(X, 16). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 263). --spec to_base36(integer()) -> binary(). -to_base36(X) -> - erlang:integer_to_binary(X, 36). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 286). --spec to_float(integer()) -> float(). -to_float(X) -> - erlang:float(X). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 67). --spec power(integer(), float()) -> {ok, float()} | {error, nil}. -power(Base, Exponent) -> - _pipe = Base, - _pipe@1 = to_float(_pipe), - gleam@float:power(_pipe@1, Exponent). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 87). --spec square_root(integer()) -> {ok, float()} | {error, nil}. -square_root(X) -> - _pipe = X, - _pipe@1 = to_float(_pipe), - gleam@float:square_root(_pipe@1). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 328). --spec compare(integer(), integer()) -> gleam@order:order(). -compare(A, B) -> - case A =:= B of - true -> - eq; - - false -> - case A < B of - true -> - lt; - - false -> - gt - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 348). --spec min(integer(), integer()) -> integer(). -min(A, B) -> - case A < B of - true -> - A; - - false -> - B - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 364). --spec max(integer(), integer()) -> integer(). -max(A, B) -> - case A > B of - true -> - A; - - false -> - B - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 303). --spec clamp(integer(), integer(), integer()) -> integer(). -clamp(X, Min_bound, Max_bound) -> - _pipe = X, - _pipe@1 = min(_pipe, Max_bound), - max(_pipe@1, Min_bound). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 385). --spec is_even(integer()) -> boolean(). -is_even(X) -> - (X rem 2) =:= 0. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 403). --spec is_odd(integer()) -> boolean(). -is_odd(X) -> - (X rem 2) /= 0. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 416). --spec negate(integer()) -> integer(). -negate(X) -> - -1 * X. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 434). --spec do_sum(list(integer()), integer()) -> integer(). -do_sum(Numbers, Initial) -> - case Numbers of - [] -> - Initial; - - [X | Rest] -> - do_sum(Rest, X + Initial) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 429). --spec sum(list(integer())) -> integer(). -sum(Numbers) -> - _pipe = Numbers, - do_sum(_pipe, 0). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 457). --spec do_product(list(integer()), integer()) -> integer(). -do_product(Numbers, Initial) -> - case Numbers of - [] -> - Initial; - - [X | Rest] -> - do_product(Rest, X * Initial) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 450). --spec product(list(integer())) -> integer(). -product(Numbers) -> - case Numbers of - [] -> - 1; - - _ -> - do_product(Numbers, 1) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 486). --spec do_digits(integer(), integer(), list(integer())) -> list(integer()). -do_digits(X, Base, Acc) -> - case absolute_value(X) < Base of - true -> - [X | Acc]; - - false -> - do_digits(case Base of - 0 -> 0; - Gleam@denominator -> X div Gleam@denominator - end, Base, [case Base of - 0 -> 0; - Gleam@denominator@1 -> X rem Gleam@denominator@1 - end | Acc]) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 479). --spec digits(integer(), integer()) -> {ok, list(integer())} | {error, nil}. -digits(X, Base) -> - case Base < 2 of - true -> - {error, nil}; - - false -> - {ok, do_digits(X, Base, [])} - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 520). --spec do_undigits(list(integer()), integer(), integer()) -> {ok, integer()} | - {error, nil}. -do_undigits(Numbers, Base, Acc) -> - case Numbers of - [] -> - {ok, Acc}; - - [Digit | _] when Digit >= Base -> - {error, nil}; - - [Digit@1 | Rest] -> - do_undigits(Rest, Base, (Acc * Base) + Digit@1) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 513). --spec undigits(list(integer()), integer()) -> {ok, integer()} | {error, nil}. -undigits(Numbers, Base) -> - case Base < 2 of - true -> - {error, nil}; - - false -> - do_undigits(Numbers, Base, 0) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 549). --spec random(integer()) -> integer(). -random(Max) -> - _pipe = (rand:uniform() * to_float(Max)), - _pipe@1 = gleam@float:floor(_pipe), - gleam@float:round(_pipe@1). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 582). --spec divide(integer(), integer()) -> {ok, integer()} | {error, nil}. -divide(Dividend, Divisor) -> - case Divisor of - 0 -> - {error, nil}; - - Divisor@1 -> - {ok, case Divisor@1 of - 0 -> 0; - Gleam@denominator -> Dividend div Gleam@denominator - end} - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 634). --spec remainder(integer(), integer()) -> {ok, integer()} | {error, nil}. -remainder(Dividend, Divisor) -> - case Divisor of - 0 -> - {error, nil}; - - Divisor@1 -> - {ok, case Divisor@1 of - 0 -> 0; - Gleam@denominator -> Dividend rem Gleam@denominator - end} - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 676). --spec modulo(integer(), integer()) -> {ok, integer()} | {error, nil}. -modulo(Dividend, Divisor) -> - case Divisor of - 0 -> - {error, nil}; - - _ -> - Remainder = case Divisor of - 0 -> 0; - Gleam@denominator -> Dividend rem Gleam@denominator - end, - case (Remainder * Divisor) < 0 of - true -> - {ok, Remainder + Divisor}; - - false -> - {ok, Remainder} - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 720). --spec floor_divide(integer(), integer()) -> {ok, integer()} | {error, nil}. -floor_divide(Dividend, Divisor) -> - case Divisor of - 0 -> - {error, nil}; - - Divisor@1 -> - case ((Dividend * Divisor@1) < 0) andalso ((case Divisor@1 of - 0 -> 0; - Gleam@denominator -> Dividend rem Gleam@denominator - end) /= 0) of - true -> - {ok, (case Divisor@1 of - 0 -> 0; - Gleam@denominator@1 -> Dividend div Gleam@denominator@1 - end) - 1}; - - false -> - {ok, case Divisor@1 of - 0 -> 0; - Gleam@denominator@2 -> Dividend div Gleam@denominator@2 - end} - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 754). --spec add(integer(), integer()) -> integer(). -add(A, B) -> - A + B. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 782). --spec multiply(integer(), integer()) -> integer(). -multiply(A, B) -> - A * B. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 815). --spec subtract(integer(), integer()) -> integer(). -subtract(A, B) -> - A - B. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 827). --spec bitwise_and(integer(), integer()) -> integer(). -bitwise_and(X, Y) -> - erlang:'band'(X, Y). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 837). --spec bitwise_not(integer()) -> integer(). -bitwise_not(X) -> - erlang:'bnot'(X). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 847). --spec bitwise_or(integer(), integer()) -> integer(). -bitwise_or(X, Y) -> - erlang:'bor'(X, Y). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 857). --spec bitwise_exclusive_or(integer(), integer()) -> integer(). -bitwise_exclusive_or(X, Y) -> - erlang:'bxor'(X, Y). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 867). --spec bitwise_shift_left(integer(), integer()) -> integer(). -bitwise_shift_left(X, Y) -> - erlang:'bsl'(X, Y). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam", 877). --spec bitwise_shift_right(integer(), integer()) -> integer(). -bitwise_shift_right(X, Y) -> - erlang:'bsr'(X, Y). diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@io.cache b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@io.cache deleted file mode 100644 index bc91bbe028e..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@io.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@io.cache_meta b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@io.cache_meta deleted file mode 100644 index e584e3c1f3a..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@io.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@io.erl b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@io.erl deleted file mode 100644 index 001819d3cf3..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@io.erl +++ /dev/null @@ -1,32 +0,0 @@ --module(gleam@io). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([print/1, print_error/1, println/1, println_error/1, debug/1]). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/io.gleam", 15). --spec print(binary()) -> nil. -print(String) -> - gleam_stdlib:print(String). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/io.gleam", 35). --spec print_error(binary()) -> nil. -print_error(String) -> - gleam_stdlib:print_error(String). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/io.gleam", 53). --spec println(binary()) -> nil. -println(String) -> - gleam_stdlib:println(String). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/io.gleam", 71). --spec println_error(binary()) -> nil. -println_error(String) -> - gleam_stdlib:println_error(String). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/io.gleam", 108). --spec debug(DSN) -> DSN. -debug(Term) -> - _pipe = Term, - _pipe@1 = gleam@string:inspect(_pipe), - gleam_stdlib:println_error(_pipe@1), - Term. diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@iterator.cache b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@iterator.cache deleted file mode 100644 index 6c03414f1aa..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@iterator.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@iterator.cache_meta b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@iterator.cache_meta deleted file mode 100644 index 20a841e5b55..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@iterator.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@iterator.erl b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@iterator.erl deleted file mode 100644 index 6537150c8c7..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@iterator.erl +++ /dev/null @@ -1,873 +0,0 @@ --module(gleam@iterator). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([unfold/2, repeatedly/1, repeat/1, from_list/1, transform/3, fold/3, run/1, to_list/1, step/1, take/2, drop/2, map/2, map2/3, append/2, flatten/1, concat/1, flat_map/2, filter/2, filter_map/2, cycle/1, find/2, find_map/2, index/1, iterate/2, take_while/2, drop_while/2, scan/3, zip/2, chunk/2, sized_chunk/2, intersperse/2, any/2, all/2, group/2, reduce/2, last/1, empty/0, once/1, range/2, single/1, interleave/2, fold_until/3, try_fold/3, first/1, at/2, length/1, each/2, yield/2]). --export_type([action/1, iterator/1, step/2, chunk/2, sized_chunk/1]). - --type action(DSX) :: stop | {continue, DSX, fun(() -> action(DSX))}. - --opaque iterator(DSY) :: {iterator, fun(() -> action(DSY))}. - --type step(DSZ, DTA) :: {next, DSZ, DTA} | done. - --type chunk(DTB, DTC) :: {another_by, - list(DTB), - DTC, - DTB, - fun(() -> action(DTB))} | - {last_by, list(DTB)}. - --type sized_chunk(DTD) :: {another, list(DTD), fun(() -> action(DTD))} | - {last, list(DTD)} | - no_more. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 37). --spec stop() -> action(any()). -stop() -> - stop. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 42). --spec do_unfold(DTG, fun((DTG) -> step(DTH, DTG))) -> fun(() -> action(DTH)). -do_unfold(Initial, F) -> - fun() -> case F(Initial) of - {next, X, Acc} -> - {continue, X, do_unfold(Acc, F)}; - - done -> - stop - end end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 75). --spec unfold(DTL, fun((DTL) -> step(DTM, DTL))) -> iterator(DTM). -unfold(Initial, F) -> - _pipe = Initial, - _pipe@1 = do_unfold(_pipe, F), - {iterator, _pipe@1}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 94). --spec repeatedly(fun(() -> DTQ)) -> iterator(DTQ). -repeatedly(F) -> - unfold(nil, fun(_) -> {next, F(), nil} end). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 109). --spec repeat(DTS) -> iterator(DTS). -repeat(X) -> - repeatedly(fun() -> X end). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 123). --spec from_list(list(DTU)) -> iterator(DTU). -from_list(List) -> - Yield = fun(Acc) -> case Acc of - [] -> - done; - - [Head | Tail] -> - {next, Head, Tail} - end end, - unfold(List, Yield). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 134). --spec do_transform( - fun(() -> action(DTX)), - DTZ, - fun((DTZ, DTX) -> step(DUA, DTZ)) -) -> fun(() -> action(DUA)). -do_transform(Continuation, State, F) -> - fun() -> case Continuation() of - stop -> - stop; - - {continue, El, Next} -> - case F(State, El) of - done -> - stop; - - {next, Yield, Next_state} -> - {continue, Yield, do_transform(Next, Next_state, F)} - end - end end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 169). --spec transform(iterator(DUE), DUG, fun((DUG, DUE) -> step(DUH, DUG))) -> iterator(DUH). -transform(Iterator, Initial, F) -> - _pipe = do_transform(erlang:element(2, Iterator), Initial, F), - {iterator, _pipe}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 178). --spec do_fold(fun(() -> action(DUL)), fun((DUN, DUL) -> DUN), DUN) -> DUN. -do_fold(Continuation, F, Accumulator) -> - case Continuation() of - {continue, Elem, Next} -> - do_fold(Next, F, F(Accumulator, Elem)); - - stop -> - Accumulator - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 206). --spec fold(iterator(DUO), DUQ, fun((DUQ, DUO) -> DUQ)) -> DUQ. -fold(Iterator, Initial, F) -> - _pipe = erlang:element(2, Iterator), - do_fold(_pipe, F, Initial). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 220). --spec run(iterator(any())) -> nil. -run(Iterator) -> - fold(Iterator, nil, fun(_, _) -> nil end). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 238). --spec to_list(iterator(DUT)) -> list(DUT). -to_list(Iterator) -> - _pipe = Iterator, - _pipe@1 = fold(_pipe, [], fun(Acc, E) -> [E | Acc] end), - lists:reverse(_pipe@1). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 266). --spec step(iterator(DUW)) -> step(DUW, iterator(DUW)). -step(Iterator) -> - case (erlang:element(2, Iterator))() of - stop -> - done; - - {continue, E, A} -> - {next, E, {iterator, A}} - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 273). --spec do_take(fun(() -> action(DVB)), integer()) -> fun(() -> action(DVB)). -do_take(Continuation, Desired) -> - fun() -> case Desired > 0 of - false -> - stop; - - true -> - case Continuation() of - stop -> - stop; - - {continue, E, Next} -> - {continue, E, do_take(Next, Desired - 1)} - end - end end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 306). --spec take(iterator(DVE), integer()) -> iterator(DVE). -take(Iterator, Desired) -> - _pipe = erlang:element(2, Iterator), - _pipe@1 = do_take(_pipe, Desired), - {iterator, _pipe@1}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 312). --spec do_drop(fun(() -> action(DVH)), integer()) -> action(DVH). -do_drop(Continuation, Desired) -> - case Continuation() of - stop -> - stop; - - {continue, E, Next} -> - case Desired > 0 of - true -> - do_drop(Next, Desired - 1); - - false -> - {continue, E, Next} - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 348). --spec drop(iterator(DVK), integer()) -> iterator(DVK). -drop(Iterator, Desired) -> - _pipe = fun() -> do_drop(erlang:element(2, Iterator), Desired) end, - {iterator, _pipe}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 353). --spec do_map(fun(() -> action(DVN)), fun((DVN) -> DVP)) -> fun(() -> action(DVP)). -do_map(Continuation, F) -> - fun() -> case Continuation() of - stop -> - stop; - - {continue, E, Continuation@1} -> - {continue, F(E), do_map(Continuation@1, F)} - end end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 379). --spec map(iterator(DVR), fun((DVR) -> DVT)) -> iterator(DVT). -map(Iterator, F) -> - _pipe = erlang:element(2, Iterator), - _pipe@1 = do_map(_pipe, F), - {iterator, _pipe@1}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 385). --spec do_map2( - fun(() -> action(DVV)), - fun(() -> action(DVX)), - fun((DVV, DVX) -> DVZ) -) -> fun(() -> action(DVZ)). -do_map2(Continuation1, Continuation2, Fun) -> - fun() -> case Continuation1() of - stop -> - stop; - - {continue, A, Next_a} -> - case Continuation2() of - stop -> - stop; - - {continue, B, Next_b} -> - {continue, Fun(A, B), do_map2(Next_a, Next_b, Fun)} - end - end end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 426). --spec map2(iterator(DWB), iterator(DWD), fun((DWB, DWD) -> DWF)) -> iterator(DWF). -map2(Iterator1, Iterator2, Fun) -> - _pipe = do_map2( - erlang:element(2, Iterator1), - erlang:element(2, Iterator2), - Fun - ), - {iterator, _pipe}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 435). --spec do_append(fun(() -> action(DWH)), fun(() -> action(DWH))) -> action(DWH). -do_append(First, Second) -> - case First() of - {continue, E, First@1} -> - {continue, E, fun() -> do_append(First@1, Second) end}; - - stop -> - Second() - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 456). --spec append(iterator(DWL), iterator(DWL)) -> iterator(DWL). -append(First, Second) -> - _pipe = fun() -> - do_append(erlang:element(2, First), erlang:element(2, Second)) - end, - {iterator, _pipe}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 461). --spec do_flatten(fun(() -> action(iterator(DWP)))) -> action(DWP). -do_flatten(Flattened) -> - case Flattened() of - stop -> - stop; - - {continue, It, Next_iterator} -> - do_append( - erlang:element(2, It), - fun() -> do_flatten(Next_iterator) end - ) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 484). --spec flatten(iterator(iterator(DWT))) -> iterator(DWT). -flatten(Iterator) -> - _pipe = fun() -> do_flatten(erlang:element(2, Iterator)) end, - {iterator, _pipe}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 504). --spec concat(list(iterator(DWX))) -> iterator(DWX). -concat(Iterators) -> - flatten(from_list(Iterators)). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 526). --spec flat_map(iterator(DXB), fun((DXB) -> iterator(DXD))) -> iterator(DXD). -flat_map(Iterator, F) -> - _pipe = Iterator, - _pipe@1 = map(_pipe, F), - flatten(_pipe@1). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 535). --spec do_filter(fun(() -> action(DXG)), fun((DXG) -> boolean())) -> action(DXG). -do_filter(Continuation, Predicate) -> - case Continuation() of - stop -> - stop; - - {continue, E, Iterator} -> - case Predicate(E) of - true -> - {continue, E, fun() -> do_filter(Iterator, Predicate) end}; - - false -> - do_filter(Iterator, Predicate) - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 568). --spec filter(iterator(DXJ), fun((DXJ) -> boolean())) -> iterator(DXJ). -filter(Iterator, Predicate) -> - _pipe = fun() -> do_filter(erlang:element(2, Iterator), Predicate) end, - {iterator, _pipe}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 576). --spec do_filter_map( - fun(() -> action(DXM)), - fun((DXM) -> {ok, DXO} | {error, any()}) -) -> action(DXO). -do_filter_map(Continuation, F) -> - case Continuation() of - stop -> - stop; - - {continue, E, Next} -> - case F(E) of - {ok, E@1} -> - {continue, E@1, fun() -> do_filter_map(Next, F) end}; - - {error, _} -> - do_filter_map(Next, F) - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 612). --spec filter_map(iterator(DXT), fun((DXT) -> {ok, DXV} | {error, any()})) -> iterator(DXV). -filter_map(Iterator, F) -> - _pipe = fun() -> do_filter_map(erlang:element(2, Iterator), F) end, - {iterator, _pipe}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 632). --spec cycle(iterator(DYA)) -> iterator(DYA). -cycle(Iterator) -> - _pipe = repeat(Iterator), - flatten(_pipe). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 678). --spec do_find(fun(() -> action(DYE)), fun((DYE) -> boolean())) -> {ok, DYE} | - {error, nil}. -do_find(Continuation, F) -> - case Continuation() of - stop -> - {error, nil}; - - {continue, E, Next} -> - case F(E) of - true -> - {ok, E}; - - false -> - do_find(Next, F) - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 712). --spec find(iterator(DYI), fun((DYI) -> boolean())) -> {ok, DYI} | {error, nil}. -find(Haystack, Is_desired) -> - _pipe = erlang:element(2, Haystack), - do_find(_pipe, Is_desired). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 720). --spec do_find_map( - fun(() -> action(DYM)), - fun((DYM) -> {ok, DYO} | {error, any()}) -) -> {ok, DYO} | {error, nil}. -do_find_map(Continuation, F) -> - case Continuation() of - stop -> - {error, nil}; - - {continue, E, Next} -> - case F(E) of - {ok, E@1} -> - {ok, E@1}; - - {error, _} -> - do_find_map(Next, F) - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 757). --spec find_map(iterator(DYU), fun((DYU) -> {ok, DYW} | {error, any()})) -> {ok, - DYW} | - {error, nil}. -find_map(Haystack, Is_desired) -> - _pipe = erlang:element(2, Haystack), - do_find_map(_pipe, Is_desired). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 765). --spec do_index(fun(() -> action(DZC)), integer()) -> fun(() -> action({DZC, - integer()})). -do_index(Continuation, Next) -> - fun() -> case Continuation() of - stop -> - stop; - - {continue, E, Continuation@1} -> - {continue, {E, Next}, do_index(Continuation@1, Next + 1)} - end end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 787). --spec index(iterator(DZF)) -> iterator({DZF, integer()}). -index(Iterator) -> - _pipe = erlang:element(2, Iterator), - _pipe@1 = do_index(_pipe, 0), - {iterator, _pipe@1}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 802). --spec iterate(DZI, fun((DZI) -> DZI)) -> iterator(DZI). -iterate(Initial, F) -> - unfold(Initial, fun(Element) -> {next, Element, F(Element)} end). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 809). --spec do_take_while(fun(() -> action(DZK)), fun((DZK) -> boolean())) -> fun(() -> action(DZK)). -do_take_while(Continuation, Predicate) -> - fun() -> case Continuation() of - stop -> - stop; - - {continue, E, Next} -> - case Predicate(E) of - false -> - stop; - - true -> - {continue, E, do_take_while(Next, Predicate)} - end - end end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 836). --spec take_while(iterator(DZN), fun((DZN) -> boolean())) -> iterator(DZN). -take_while(Iterator, Predicate) -> - _pipe = erlang:element(2, Iterator), - _pipe@1 = do_take_while(_pipe, Predicate), - {iterator, _pipe@1}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 845). --spec do_drop_while(fun(() -> action(DZQ)), fun((DZQ) -> boolean())) -> action(DZQ). -do_drop_while(Continuation, Predicate) -> - case Continuation() of - stop -> - stop; - - {continue, E, Next} -> - case Predicate(E) of - false -> - {continue, E, Next}; - - true -> - do_drop_while(Next, Predicate) - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 871). --spec drop_while(iterator(DZT), fun((DZT) -> boolean())) -> iterator(DZT). -drop_while(Iterator, Predicate) -> - _pipe = fun() -> do_drop_while(erlang:element(2, Iterator), Predicate) end, - {iterator, _pipe}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 879). --spec do_scan(fun(() -> action(DZW)), fun((DZY, DZW) -> DZY), DZY) -> fun(() -> action(DZY)). -do_scan(Continuation, F, Accumulator) -> - fun() -> case Continuation() of - stop -> - stop; - - {continue, El, Next} -> - Accumulated = F(Accumulator, El), - {continue, Accumulated, do_scan(Next, F, Accumulated)} - end end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 909). --spec scan(iterator(EAA), EAC, fun((EAC, EAA) -> EAC)) -> iterator(EAC). -scan(Iterator, Initial, F) -> - _pipe = erlang:element(2, Iterator), - _pipe@1 = do_scan(_pipe, F, Initial), - {iterator, _pipe@1}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 919). --spec do_zip(fun(() -> action(EAE)), fun(() -> action(EAG))) -> fun(() -> action({EAE, - EAG})). -do_zip(Left, Right) -> - fun() -> case Left() of - stop -> - stop; - - {continue, El_left, Next_left} -> - case Right() of - stop -> - stop; - - {continue, El_right, Next_right} -> - {continue, - {El_left, El_right}, - do_zip(Next_left, Next_right)} - end - end end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 948). --spec zip(iterator(EAJ), iterator(EAL)) -> iterator({EAJ, EAL}). -zip(Left, Right) -> - _pipe = do_zip(erlang:element(2, Left), erlang:element(2, Right)), - {iterator, _pipe}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 959). --spec next_chunk(fun(() -> action(EAO)), fun((EAO) -> EAQ), EAQ, list(EAO)) -> chunk(EAO, EAQ). -next_chunk(Continuation, F, Previous_key, Current_chunk) -> - case Continuation() of - stop -> - {last_by, lists:reverse(Current_chunk)}; - - {continue, E, Next} -> - Key = F(E), - case Key =:= Previous_key of - true -> - next_chunk(Next, F, Key, [E | Current_chunk]); - - false -> - {another_by, lists:reverse(Current_chunk), Key, E, Next} - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 977). --spec do_chunk(fun(() -> action(EAU)), fun((EAU) -> EAW), EAW, EAU) -> action(list(EAU)). -do_chunk(Continuation, F, Previous_key, Previous_element) -> - case next_chunk(Continuation, F, Previous_key, [Previous_element]) of - {last_by, Chunk} -> - {continue, Chunk, fun stop/0}; - - {another_by, Chunk@1, Key, El, Next} -> - {continue, Chunk@1, fun() -> do_chunk(Next, F, Key, El) end} - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 1002). --spec chunk(iterator(EAZ), fun((EAZ) -> any())) -> iterator(list(EAZ)). -chunk(Iterator, F) -> - _pipe = fun() -> case (erlang:element(2, Iterator))() of - stop -> - stop; - - {continue, E, Next} -> - do_chunk(Next, F, F(E), E) - end end, - {iterator, _pipe}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 1022). --spec next_sized_chunk(fun(() -> action(EBE)), integer(), list(EBE)) -> sized_chunk(EBE). -next_sized_chunk(Continuation, Left, Current_chunk) -> - case Continuation() of - stop -> - case Current_chunk of - [] -> - no_more; - - Remaining -> - {last, lists:reverse(Remaining)} - end; - - {continue, E, Next} -> - Chunk = [E | Current_chunk], - case Left > 1 of - false -> - {another, lists:reverse(Chunk), Next}; - - true -> - next_sized_chunk(Next, Left - 1, Chunk) - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 1043). --spec do_sized_chunk(fun(() -> action(EBI)), integer()) -> fun(() -> action(list(EBI))). -do_sized_chunk(Continuation, Count) -> - fun() -> case next_sized_chunk(Continuation, Count, []) of - no_more -> - stop; - - {last, Chunk} -> - {continue, Chunk, fun stop/0}; - - {another, Chunk@1, Next_element} -> - {continue, Chunk@1, do_sized_chunk(Next_element, Count)} - end end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 1080). --spec sized_chunk(iterator(EBM), integer()) -> iterator(list(EBM)). -sized_chunk(Iterator, Count) -> - _pipe = erlang:element(2, Iterator), - _pipe@1 = do_sized_chunk(_pipe, Count), - {iterator, _pipe@1}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 1089). --spec do_intersperse(fun(() -> action(EBQ)), EBQ) -> action(EBQ). -do_intersperse(Continuation, Separator) -> - case Continuation() of - stop -> - stop; - - {continue, E, Next} -> - Next_interspersed = fun() -> do_intersperse(Next, Separator) end, - {continue, Separator, fun() -> {continue, E, Next_interspersed} end} - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 1128). --spec intersperse(iterator(EBT), EBT) -> iterator(EBT). -intersperse(Iterator, Elem) -> - _pipe = fun() -> case (erlang:element(2, Iterator))() of - stop -> - stop; - - {continue, E, Next} -> - {continue, E, fun() -> do_intersperse(Next, Elem) end} - end end, - {iterator, _pipe}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 1141). --spec do_any(fun(() -> action(EBW)), fun((EBW) -> boolean())) -> boolean(). -do_any(Continuation, Predicate) -> - case Continuation() of - stop -> - false; - - {continue, E, Next} -> - case Predicate(E) of - true -> - true; - - false -> - do_any(Next, Predicate) - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 1182). --spec any(iterator(EBY), fun((EBY) -> boolean())) -> boolean(). -any(Iterator, Predicate) -> - _pipe = erlang:element(2, Iterator), - do_any(_pipe, Predicate). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 1190). --spec do_all(fun(() -> action(ECA)), fun((ECA) -> boolean())) -> boolean(). -do_all(Continuation, Predicate) -> - case Continuation() of - stop -> - true; - - {continue, E, Next} -> - case Predicate(E) of - true -> - do_all(Next, Predicate); - - false -> - false - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 1231). --spec all(iterator(ECC), fun((ECC) -> boolean())) -> boolean(). -all(Iterator, Predicate) -> - _pipe = erlang:element(2, Iterator), - do_all(_pipe, Predicate). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 1239). --spec update_group_with(ECE) -> fun((gleam@option:option(list(ECE))) -> list(ECE)). -update_group_with(El) -> - fun(Maybe_group) -> case Maybe_group of - {some, Group} -> - [El | Group]; - - none -> - [El] - end end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 1248). --spec group_updater(fun((ECI) -> ECJ)) -> fun((gleam@dict:dict(ECJ, list(ECI)), ECI) -> gleam@dict:dict(ECJ, list(ECI))). -group_updater(F) -> - fun(Groups, Elem) -> _pipe = Groups, - gleam@dict:upsert(_pipe, F(Elem), update_group_with(Elem)) end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 1270). --spec group(iterator(ECQ), fun((ECQ) -> ECS)) -> gleam@dict:dict(ECS, list(ECQ)). -group(Iterator, Key) -> - _pipe = Iterator, - _pipe@1 = fold(_pipe, gleam@dict:new(), group_updater(Key)), - gleam@dict:map_values(_pipe@1, fun(_, Group) -> lists:reverse(Group) end). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 1300). --spec reduce(iterator(ECW), fun((ECW, ECW) -> ECW)) -> {ok, ECW} | {error, nil}. -reduce(Iterator, F) -> - case (erlang:element(2, Iterator))() of - stop -> - {error, nil}; - - {continue, E, Next} -> - _pipe = do_fold(Next, F, E), - {ok, _pipe} - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 1330). --spec last(iterator(EDA)) -> {ok, EDA} | {error, nil}. -last(Iterator) -> - _pipe = Iterator, - reduce(_pipe, fun(_, Elem) -> Elem end). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 1344). --spec empty() -> iterator(any()). -empty() -> - {iterator, fun stop/0}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 1357). --spec once(fun(() -> EDG)) -> iterator(EDG). -once(F) -> - _pipe = fun() -> {continue, F(), fun stop/0} end, - {iterator, _pipe}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 657). --spec range(integer(), integer()) -> iterator(integer()). -range(Start, Stop) -> - case gleam@int:compare(Start, Stop) of - eq -> - once(fun() -> Start end); - - gt -> - unfold(Start, fun(Current) -> case Current < Stop of - false -> - {next, Current, Current - 1}; - - true -> - done - end end); - - lt -> - unfold(Start, fun(Current@1) -> case Current@1 > Stop of - false -> - {next, Current@1, Current@1 + 1}; - - true -> - done - end end) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 1371). --spec single(EDI) -> iterator(EDI). -single(Elem) -> - once(fun() -> Elem end). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 1375). --spec do_interleave(fun(() -> action(EDK)), fun(() -> action(EDK))) -> action(EDK). -do_interleave(Current, Next) -> - case Current() of - stop -> - Next(); - - {continue, E, Next_other} -> - {continue, E, fun() -> do_interleave(Next, Next_other) end} - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 1405). --spec interleave(iterator(EDO), iterator(EDO)) -> iterator(EDO). -interleave(Left, Right) -> - _pipe = fun() -> - do_interleave(erlang:element(2, Left), erlang:element(2, Right)) - end, - {iterator, _pipe}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 1413). --spec do_fold_until( - fun(() -> action(EDS)), - fun((EDU, EDS) -> gleam@list:continue_or_stop(EDU)), - EDU -) -> EDU. -do_fold_until(Continuation, F, Accumulator) -> - case Continuation() of - stop -> - Accumulator; - - {continue, Elem, Next} -> - case F(Accumulator, Elem) of - {continue, Accumulator@1} -> - do_fold_until(Next, F, Accumulator@1); - - {stop, Accumulator@2} -> - Accumulator@2 - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 1452). --spec fold_until( - iterator(EDW), - EDY, - fun((EDY, EDW) -> gleam@list:continue_or_stop(EDY)) -) -> EDY. -fold_until(Iterator, Initial, F) -> - _pipe = erlang:element(2, Iterator), - do_fold_until(_pipe, F, Initial). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 1461). --spec do_try_fold( - fun(() -> action(EEA)), - fun((EEC, EEA) -> {ok, EEC} | {error, EED}), - EEC -) -> {ok, EEC} | {error, EED}. -do_try_fold(Continuation, F, Accumulator) -> - case Continuation() of - stop -> - {ok, Accumulator}; - - {continue, Elem, Next} -> - case F(Accumulator, Elem) of - {ok, Result} -> - do_try_fold(Next, F, Result); - - {error, _} = Error -> - Error - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 1496). --spec try_fold(iterator(EEI), EEK, fun((EEK, EEI) -> {ok, EEK} | {error, EEL})) -> {ok, - EEK} | - {error, EEL}. -try_fold(Iterator, Initial, F) -> - _pipe = erlang:element(2, Iterator), - do_try_fold(_pipe, F, Initial). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 1519). --spec first(iterator(EEQ)) -> {ok, EEQ} | {error, nil}. -first(Iterator) -> - case (erlang:element(2, Iterator))() of - stop -> - {error, nil}; - - {continue, E, _} -> - {ok, E} - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 1549). --spec at(iterator(EEU), integer()) -> {ok, EEU} | {error, nil}. -at(Iterator, Index) -> - _pipe = Iterator, - _pipe@1 = drop(_pipe, Index), - first(_pipe@1). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 1555). --spec do_length(fun(() -> action(any())), integer()) -> integer(). -do_length(Continuation, Length) -> - case Continuation() of - stop -> - Length; - - {continue, _, Next} -> - do_length(Next, Length + 1) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 1579). --spec length(iterator(any())) -> integer(). -length(Iterator) -> - _pipe = erlang:element(2, Iterator), - do_length(_pipe, 0). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 1601). --spec each(iterator(EFC), fun((EFC) -> any())) -> nil. -each(Iterator, F) -> - _pipe = Iterator, - _pipe@1 = map(_pipe, F), - run(_pipe@1). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam", 1626). --spec yield(EFF, fun(() -> iterator(EFF))) -> iterator(EFF). -yield(Element, Next) -> - {iterator, - fun() -> - {continue, Element, fun() -> (erlang:element(2, Next()))() end} - end}. diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@list.cache b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@list.cache deleted file mode 100644 index ee14fb148bd..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@list.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@list.cache_meta b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@list.cache_meta deleted file mode 100644 index 9a43a6fe3fc..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@list.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@list.erl b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@list.erl deleted file mode 100644 index 7cedffea7ac..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@list.erl +++ /dev/null @@ -1,1442 +0,0 @@ --module(gleam@list). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([length/1, reverse/1, is_empty/1, contains/2, first/1, rest/1, filter/2, filter_map/2, map/2, map2/3, index_map/2, try_map/2, drop/2, take/2, new/0, wrap/1, append/2, prepend/2, concat/1, flatten/1, flat_map/2, fold/3, count/2, group/2, map_fold/3, fold_right/3, index_fold/3, try_fold/3, fold_until/3, find/2, find_map/2, all/2, any/2, zip/2, strict_zip/2, unzip/1, intersperse/2, unique/1, sort/2, range/2, repeat/2, split/2, split_while/2, key_find/2, key_filter/2, pop/2, pop_map/2, key_pop/2, key_set/3, each/2, try_each/2, partition/2, permutations/1, window/2, window_by_2/1, drop_while/2, take_while/2, chunk/2, sized_chunk/2, reduce/2, scan/3, last/1, combinations/2, combination_pairs/1, transpose/1, interleave/1, shuffle/1]). --export_type([continue_or_stop/1, sorting/0]). - --type continue_or_stop(AAO) :: {continue, AAO} | {stop, AAO}. - --type sorting() :: ascending | descending. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 61). --spec count_length(list(any()), integer()) -> integer(). -count_length(List, Count) -> - case List of - [_ | List@1] -> - count_length(List@1, Count + 1); - - _ -> - Count - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 57). --spec length(list(any())) -> integer(). -length(List) -> - erlang:length(List). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 130). --spec do_reverse(list(AAY), list(AAY)) -> list(AAY). -do_reverse(Remaining, Accumulator) -> - case Remaining of - [] -> - Accumulator; - - [Item | Rest] -> - do_reverse(Rest, [Item | Accumulator]) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 126). --spec reverse(list(AAV)) -> list(AAV). -reverse(List) -> - lists:reverse(List). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 158). --spec is_empty(list(any())) -> boolean(). -is_empty(List) -> - List =:= []. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 194). --spec contains(list(ABE), ABE) -> boolean(). -contains(List, Elem) -> - case List of - [] -> - false; - - [First | _] when First =:= Elem -> - true; - - [_ | Rest] -> - contains(Rest, Elem) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 221). --spec first(list(ABG)) -> {ok, ABG} | {error, nil}. -first(List) -> - case List of - [] -> - {error, nil}; - - [X | _] -> - {ok, X} - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 250). --spec rest(list(ABK)) -> {ok, list(ABK)} | {error, nil}. -rest(List) -> - case List of - [] -> - {error, nil}; - - [_ | Rest] -> - {ok, Rest} - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 257). --spec update_group(fun((ABP) -> ABQ)) -> fun((gleam@dict:dict(ABQ, list(ABP)), ABP) -> gleam@dict:dict(ABQ, list(ABP))). -update_group(F) -> - fun(Groups, Elem) -> case gleam@dict:get(Groups, F(Elem)) of - {ok, Existing} -> - gleam@dict:insert(Groups, F(Elem), [Elem | Existing]); - - {error, _} -> - gleam@dict:insert(Groups, F(Elem), [Elem]) - end end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 302). --spec do_filter(list(ACD), fun((ACD) -> boolean()), list(ACD)) -> list(ACD). -do_filter(List, Fun, Acc) -> - case List of - [] -> - lists:reverse(Acc); - - [First | Rest] -> - New_acc = case Fun(First) of - true -> - [First | Acc]; - - false -> - Acc - end, - do_filter(Rest, Fun, New_acc) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 330). --spec filter(list(ACH), fun((ACH) -> boolean())) -> list(ACH). -filter(List, Predicate) -> - do_filter(List, Predicate, []). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 334). --spec do_filter_map( - list(ACK), - fun((ACK) -> {ok, ACM} | {error, any()}), - list(ACM) -) -> list(ACM). -do_filter_map(List, Fun, Acc) -> - case List of - [] -> - lists:reverse(Acc); - - [First | Rest] -> - New_acc = case Fun(First) of - {ok, First@1} -> - [First@1 | Acc]; - - {error, _} -> - Acc - end, - do_filter_map(Rest, Fun, New_acc) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 366). --spec filter_map(list(ACS), fun((ACS) -> {ok, ACU} | {error, any()})) -> list(ACU). -filter_map(List, Fun) -> - do_filter_map(List, Fun, []). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 370). --spec do_map(list(ACZ), fun((ACZ) -> ADB), list(ADB)) -> list(ADB). -do_map(List, Fun, Acc) -> - case List of - [] -> - lists:reverse(Acc); - - [First | Rest] -> - do_map(Rest, Fun, [Fun(First) | Acc]) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 387). --spec map(list(ADE), fun((ADE) -> ADG)) -> list(ADG). -map(List, Fun) -> - do_map(List, Fun, []). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 411). --spec do_map2(list(ADO), list(ADQ), fun((ADO, ADQ) -> ADS), list(ADS)) -> list(ADS). -do_map2(List1, List2, Fun, Acc) -> - case {List1, List2} of - {[], _} -> - lists:reverse(Acc); - - {_, []} -> - lists:reverse(Acc); - - {[A | As_], [B | Bs]} -> - do_map2(As_, Bs, Fun, [Fun(A, B) | Acc]) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 407). --spec map2(list(ADI), list(ADK), fun((ADI, ADK) -> ADM)) -> list(ADM). -map2(List1, List2, Fun) -> - do_map2(List1, List2, Fun, []). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 449). --spec do_index_map( - list(AEA), - fun((AEA, integer()) -> AEC), - integer(), - list(AEC) -) -> list(AEC). -do_index_map(List, Fun, Index, Acc) -> - case List of - [] -> - lists:reverse(Acc); - - [First | Rest] -> - Acc@1 = [Fun(First, Index) | Acc], - do_index_map(Rest, Fun, Index + 1, Acc@1) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 477). --spec index_map(list(AEF), fun((AEF, integer()) -> AEH)) -> list(AEH). -index_map(List, Fun) -> - do_index_map(List, Fun, 0, []). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 481). --spec do_try_map(list(AEJ), fun((AEJ) -> {ok, AEL} | {error, AEM}), list(AEL)) -> {ok, - list(AEL)} | - {error, AEM}. -do_try_map(List, Fun, Acc) -> - case List of - [] -> - {ok, lists:reverse(Acc)}; - - [First | Rest] -> - case Fun(First) of - {ok, First@1} -> - do_try_map(Rest, Fun, [First@1 | Acc]); - - {error, Error} -> - {error, Error} - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 528). --spec try_map(list(AET), fun((AET) -> {ok, AEV} | {error, AEW})) -> {ok, - list(AEV)} | - {error, AEW}. -try_map(List, Fun) -> - do_try_map(List, Fun, []). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 555). --spec drop(list(AFC), integer()) -> list(AFC). -drop(List, N) -> - case N =< 0 of - true -> - List; - - false -> - case List of - [] -> - []; - - [_ | Rest] -> - drop(Rest, N - 1) - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 566). --spec do_take(list(AFF), integer(), list(AFF)) -> list(AFF). -do_take(List, N, Acc) -> - case N =< 0 of - true -> - lists:reverse(Acc); - - false -> - case List of - [] -> - lists:reverse(Acc); - - [First | Rest] -> - do_take(Rest, N - 1, [First | Acc]) - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 597). --spec take(list(AFJ), integer()) -> list(AFJ). -take(List, N) -> - do_take(List, N, []). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 610). --spec new() -> list(any()). -new() -> - []. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 630). --spec wrap(AFO) -> list(AFO). -wrap(Item) -> - [Item]. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 651). --spec do_append(list(AFU), list(AFU)) -> list(AFU). -do_append(First, Second) -> - case First of - [] -> - Second; - - [Item | Rest] -> - do_append(Rest, [Item | Second]) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 647). --spec append(list(AFQ), list(AFQ)) -> list(AFQ). -append(First, Second) -> - lists:append(First, Second). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 671). --spec prepend(list(AFY), AFY) -> list(AFY). -prepend(List, Item) -> - [Item | List]. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 676). --spec reverse_and_prepend(list(AGB), list(AGB)) -> list(AGB). -reverse_and_prepend(Prefix, Suffix) -> - case Prefix of - [] -> - Suffix; - - [First | Rest] -> - reverse_and_prepend(Rest, [First | Suffix]) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 683). --spec do_concat(list(list(AGF)), list(AGF)) -> list(AGF). -do_concat(Lists, Acc) -> - case Lists of - [] -> - lists:reverse(Acc); - - [List | Further_lists] -> - do_concat(Further_lists, reverse_and_prepend(List, Acc)) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 703). --spec concat(list(list(AGK))) -> list(AGK). -concat(Lists) -> - do_concat(Lists, []). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 719). --spec flatten(list(list(AGO))) -> list(AGO). -flatten(Lists) -> - do_concat(Lists, []). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 732). --spec flat_map(list(AGS), fun((AGS) -> list(AGU))) -> list(AGU). -flat_map(List, Fun) -> - _pipe = map(List, Fun), - flatten(_pipe). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 745). --spec fold(list(AGX), AGZ, fun((AGZ, AGX) -> AGZ)) -> AGZ. -fold(List, Initial, Fun) -> - case List of - [] -> - Initial; - - [X | Rest] -> - fold(Rest, Fun(Initial, X), Fun) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 90). --spec count(list(AAT), fun((AAT) -> boolean())) -> integer(). -count(List, Predicate) -> - fold(List, 0, fun(Acc, Value) -> case Predicate(Value) of - true -> - Acc + 1; - - false -> - Acc - end end). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 298). --spec group(list(ABX), fun((ABX) -> ABZ)) -> gleam@dict:dict(ABZ, list(ABX)). -group(List, Key) -> - fold(List, gleam@dict:new(), update_group(Key)). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 436). --spec map_fold(list(ADV), ADX, fun((ADX, ADV) -> {ADX, ADY})) -> {ADX, - list(ADY)}. -map_fold(List, Initial, Fun) -> - _pipe = fold( - List, - {Initial, []}, - fun(Acc, Item) -> - {Current_acc, Items} = Acc, - {Next_acc, Next_item} = Fun(Current_acc, Item), - {Next_acc, [Next_item | Items]} - end - ), - gleam@pair:map_second(_pipe, fun lists:reverse/1). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 767). --spec fold_right(list(AHA), AHC, fun((AHC, AHA) -> AHC)) -> AHC. -fold_right(List, Initial, Fun) -> - case List of - [] -> - Initial; - - [X | Rest] -> - Fun(fold_right(Rest, Initial, Fun), X) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 778). --spec do_index_fold( - list(AHD), - AHF, - fun((AHF, AHD, integer()) -> AHF), - integer() -) -> AHF. -do_index_fold(Over, Acc, With, Index) -> - case Over of - [] -> - Acc; - - [First | Rest] -> - do_index_fold(Rest, With(Acc, First, Index), With, Index + 1) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 800). --spec index_fold(list(AHG), AHI, fun((AHI, AHG, integer()) -> AHI)) -> AHI. -index_fold(List, Initial, Fun) -> - do_index_fold(List, Initial, Fun, 0). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 827). --spec try_fold(list(AHJ), AHL, fun((AHL, AHJ) -> {ok, AHL} | {error, AHM})) -> {ok, - AHL} | - {error, AHM}. -try_fold(List, Initial, Fun) -> - case List of - [] -> - {ok, Initial}; - - [First | Rest] -> - case Fun(Initial, First) of - {ok, Result} -> - try_fold(Rest, Result, Fun); - - {error, _} = Error -> - Error - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 866). --spec fold_until(list(AHR), AHT, fun((AHT, AHR) -> continue_or_stop(AHT))) -> AHT. -fold_until(List, Initial, Fun) -> - case List of - [] -> - Initial; - - [First | Rest] -> - case Fun(Initial, First) of - {continue, Next_accumulator} -> - fold_until(Rest, Next_accumulator, Fun); - - {stop, B} -> - B - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 903). --spec find(list(AHV), fun((AHV) -> boolean())) -> {ok, AHV} | {error, nil}. -find(List, Is_desired) -> - case List of - [] -> - {error, nil}; - - [X | Rest] -> - case Is_desired(X) of - true -> - {ok, X}; - - _ -> - find(Rest, Is_desired) - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 939). --spec find_map(list(AHZ), fun((AHZ) -> {ok, AIB} | {error, any()})) -> {ok, AIB} | - {error, nil}. -find_map(List, Fun) -> - case List of - [] -> - {error, nil}; - - [X | Rest] -> - case Fun(X) of - {ok, X@1} -> - {ok, X@1}; - - _ -> - find_map(Rest, Fun) - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 974). --spec all(list(AIH), fun((AIH) -> boolean())) -> boolean(). -all(List, Predicate) -> - case List of - [] -> - true; - - [First | Rest] -> - case Predicate(First) of - true -> - all(Rest, Predicate); - - false -> - false - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1011). --spec any(list(AIJ), fun((AIJ) -> boolean())) -> boolean(). -any(List, Predicate) -> - case List of - [] -> - false; - - [First | Rest] -> - case Predicate(First) of - true -> - true; - - false -> - any(Rest, Predicate) - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1022). --spec do_zip(list(AIL), list(AIN), list({AIL, AIN})) -> list({AIL, AIN}). -do_zip(One, Other, Acc) -> - case {One, Other} of - {[First_one | Rest_one], [First_other | Rest_other]} -> - do_zip(Rest_one, Rest_other, [{First_one, First_other} | Acc]); - - {_, _} -> - lists:reverse(Acc) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1057). --spec zip(list(AIR), list(AIT)) -> list({AIR, AIT}). -zip(List, Other) -> - do_zip(List, Other, []). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1087). --spec strict_zip(list(AIW), list(AIY)) -> {ok, list({AIW, AIY})} | {error, nil}. -strict_zip(List, Other) -> - case erlang:length(List) =:= erlang:length(Other) of - true -> - {ok, zip(List, Other)}; - - false -> - {error, nil} - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1097). --spec do_unzip(list({AJD, AJE}), list(AJD), list(AJE)) -> {list(AJD), list(AJE)}. -do_unzip(Input, One, Other) -> - case Input of - [] -> - {lists:reverse(One), lists:reverse(Other)}; - - [{First_one, First_other} | Rest] -> - do_unzip(Rest, [First_one | One], [First_other | Other]) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1123). --spec unzip(list({AJK, AJL})) -> {list(AJK), list(AJL)}. -unzip(Input) -> - do_unzip(Input, [], []). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1127). --spec do_intersperse(list(AJP), AJP, list(AJP)) -> list(AJP). -do_intersperse(List, Separator, Acc) -> - case List of - [] -> - lists:reverse(Acc); - - [X | Rest] -> - do_intersperse(Rest, Separator, [X, Separator | Acc]) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1150). --spec intersperse(list(AJT), AJT) -> list(AJT). -intersperse(List, Elem) -> - case List of - [] -> - List; - - [_] -> - List; - - [X | Rest] -> - do_intersperse(Rest, Elem, [X]) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1168). --spec unique(list(AJW)) -> list(AJW). -unique(List) -> - case List of - [] -> - []; - - [X | Rest] -> - [X | unique(filter(Rest, fun(Y) -> Y /= X end))] - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1249). --spec sequences( - list(AKC), - fun((AKC, AKC) -> gleam@order:order()), - list(AKC), - sorting(), - AKC, - list(list(AKC)) -) -> list(list(AKC)). -sequences(List, Compare, Growing, Direction, Prev, Acc) -> - Growing@1 = [Prev | Growing], - case List of - [] -> - case Direction of - ascending -> - [do_reverse(Growing@1, []) | Acc]; - - descending -> - [Growing@1 | Acc] - end; - - [New | Rest] -> - case {Compare(Prev, New), Direction} of - {gt, descending} -> - sequences(Rest, Compare, Growing@1, Direction, New, Acc); - - {lt, ascending} -> - sequences(Rest, Compare, Growing@1, Direction, New, Acc); - - {eq, ascending} -> - sequences(Rest, Compare, Growing@1, Direction, New, Acc); - - {gt, ascending} -> - Acc@1 = case Direction of - ascending -> - [do_reverse(Growing@1, []) | Acc]; - - descending -> - [Growing@1 | Acc] - end, - case Rest of - [] -> - [[New] | Acc@1]; - - [Next | Rest@1] -> - Direction@1 = case Compare(New, Next) of - lt -> - ascending; - - eq -> - ascending; - - gt -> - descending - end, - sequences( - Rest@1, - Compare, - [New], - Direction@1, - Next, - Acc@1 - ) - end; - - {lt, descending} -> - Acc@1 = case Direction of - ascending -> - [do_reverse(Growing@1, []) | Acc]; - - descending -> - [Growing@1 | Acc] - end, - case Rest of - [] -> - [[New] | Acc@1]; - - [Next | Rest@1] -> - Direction@1 = case Compare(New, Next) of - lt -> - ascending; - - eq -> - ascending; - - gt -> - descending - end, - sequences( - Rest@1, - Compare, - [New], - Direction@1, - Next, - Acc@1 - ) - end; - - {eq, descending} -> - Acc@1 = case Direction of - ascending -> - [do_reverse(Growing@1, []) | Acc]; - - descending -> - [Growing@1 | Acc] - end, - case Rest of - [] -> - [[New] | Acc@1]; - - [Next | Rest@1] -> - Direction@1 = case Compare(New, Next) of - lt -> - ascending; - - eq -> - ascending; - - gt -> - descending - end, - sequences( - Rest@1, - Compare, - [New], - Direction@1, - Next, - Acc@1 - ) - end - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1397). --spec merge_ascendings( - list(AKZ), - list(AKZ), - fun((AKZ, AKZ) -> gleam@order:order()), - list(AKZ) -) -> list(AKZ). -merge_ascendings(List1, List2, Compare, Acc) -> - case {List1, List2} of - {[], List} -> - do_reverse(List, Acc); - - {List, []} -> - do_reverse(List, Acc); - - {[First1 | Rest1], [First2 | Rest2]} -> - case Compare(First1, First2) of - lt -> - merge_ascendings(Rest1, List2, Compare, [First1 | Acc]); - - gt -> - merge_ascendings(List1, Rest2, Compare, [First2 | Acc]); - - eq -> - merge_ascendings(List1, Rest2, Compare, [First2 | Acc]) - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1350). --spec merge_ascending_pairs( - list(list(AKN)), - fun((AKN, AKN) -> gleam@order:order()), - list(list(AKN)) -) -> list(list(AKN)). -merge_ascending_pairs(Sequences, Compare, Acc) -> - case Sequences of - [] -> - do_reverse(Acc, []); - - [Sequence] -> - do_reverse([do_reverse(Sequence, []) | Acc], []); - - [Ascending1, Ascending2 | Rest] -> - Descending = merge_ascendings(Ascending1, Ascending2, Compare, []), - merge_ascending_pairs(Rest, Compare, [Descending | Acc]) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1424). --spec merge_descendings( - list(ALE), - list(ALE), - fun((ALE, ALE) -> gleam@order:order()), - list(ALE) -) -> list(ALE). -merge_descendings(List1, List2, Compare, Acc) -> - case {List1, List2} of - {[], List} -> - do_reverse(List, Acc); - - {List, []} -> - do_reverse(List, Acc); - - {[First1 | Rest1], [First2 | Rest2]} -> - case Compare(First1, First2) of - lt -> - merge_descendings(List1, Rest2, Compare, [First2 | Acc]); - - gt -> - merge_descendings(Rest1, List2, Compare, [First1 | Acc]); - - eq -> - merge_descendings(Rest1, List2, Compare, [First1 | Acc]) - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1372). --spec merge_descending_pairs( - list(list(AKT)), - fun((AKT, AKT) -> gleam@order:order()), - list(list(AKT)) -) -> list(list(AKT)). -merge_descending_pairs(Sequences, Compare, Acc) -> - case Sequences of - [] -> - do_reverse(Acc, []); - - [Sequence] -> - do_reverse([do_reverse(Sequence, []) | Acc], []); - - [Descending1, Descending2 | Rest] -> - Ascending = merge_descendings(Descending1, Descending2, Compare, []), - merge_descending_pairs(Rest, Compare, [Ascending | Acc]) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1316). --spec merge_all( - list(list(AKJ)), - sorting(), - fun((AKJ, AKJ) -> gleam@order:order()) -) -> list(AKJ). -merge_all(Sequences, Direction, Compare) -> - case {Sequences, Direction} of - {[], _} -> - []; - - {[Sequence], ascending} -> - Sequence; - - {[Sequence@1], descending} -> - do_reverse(Sequence@1, []); - - {_, ascending} -> - Sequences@1 = merge_ascending_pairs(Sequences, Compare, []), - merge_all(Sequences@1, descending, Compare); - - {_, descending} -> - Sequences@2 = merge_descending_pairs(Sequences, Compare, []), - merge_all(Sequences@2, ascending, Compare) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1187). --spec sort(list(AJZ), fun((AJZ, AJZ) -> gleam@order:order())) -> list(AJZ). -sort(List, Compare) -> - case List of - [] -> - []; - - [X] -> - [X]; - - [X@1, Y | Rest] -> - Direction = case Compare(X@1, Y) of - lt -> - ascending; - - eq -> - ascending; - - gt -> - descending - end, - Sequences = sequences(Rest, Compare, [X@1], Direction, Y, []), - merge_all(Sequences, ascending, Compare) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1464). --spec tail_recursive_range(integer(), integer(), list(integer())) -> list(integer()). -tail_recursive_range(Start, Stop, Acc) -> - case gleam@int:compare(Start, Stop) of - eq -> - [Stop | Acc]; - - gt -> - tail_recursive_range(Start, Stop + 1, [Stop | Acc]); - - lt -> - tail_recursive_range(Start, Stop - 1, [Stop | Acc]) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1460). --spec range(integer(), integer()) -> list(integer()). -range(Start, Stop) -> - tail_recursive_range(Start, Stop, []). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1472). --spec do_repeat(ALM, integer(), list(ALM)) -> list(ALM). -do_repeat(Item, Times, Acc) -> - case Times =< 0 of - true -> - Acc; - - false -> - do_repeat(Item, Times - 1, [Item | Acc]) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1493). --spec repeat(ALP, integer()) -> list(ALP). -repeat(A, Times) -> - do_repeat(A, Times, []). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1497). --spec do_split(list(ALR), integer(), list(ALR)) -> {list(ALR), list(ALR)}. -do_split(List, N, Taken) -> - case N =< 0 of - true -> - {lists:reverse(Taken), List}; - - false -> - case List of - [] -> - {lists:reverse(Taken), []}; - - [First | Rest] -> - do_split(Rest, N - 1, [First | Taken]) - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1530). --spec split(list(ALW), integer()) -> {list(ALW), list(ALW)}. -split(List, Index) -> - do_split(List, Index, []). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1534). --spec do_split_while(list(AMA), fun((AMA) -> boolean()), list(AMA)) -> {list(AMA), - list(AMA)}. -do_split_while(List, F, Acc) -> - case List of - [] -> - {lists:reverse(Acc), []}; - - [First | Rest] -> - case F(First) of - false -> - {lists:reverse(Acc), List}; - - _ -> - do_split_while(Rest, F, [First | Acc]) - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1567). --spec split_while(list(AMF), fun((AMF) -> boolean())) -> {list(AMF), list(AMF)}. -split_while(List, Predicate) -> - do_split_while(List, Predicate, []). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1599). --spec key_find(list({AMJ, AMK}), AMJ) -> {ok, AMK} | {error, nil}. -key_find(Keyword_list, Desired_key) -> - find_map( - Keyword_list, - fun(Keyword) -> - {Key, Value} = Keyword, - case Key =:= Desired_key of - true -> - {ok, Value}; - - false -> - {error, nil} - end - end - ). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1630). --spec key_filter(list({AMO, AMP}), AMO) -> list(AMP). -key_filter(Keyword_list, Desired_key) -> - filter_map( - Keyword_list, - fun(Keyword) -> - {Key, Value} = Keyword, - case Key =:= Desired_key of - true -> - {ok, Value}; - - false -> - {error, nil} - end - end - ). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1643). --spec do_pop(list(BEX), fun((BEX) -> boolean()), list(BEX)) -> {ok, - {BEX, list(BEX)}} | - {error, nil}. -do_pop(Haystack, Predicate, Checked) -> - case Haystack of - [] -> - {error, nil}; - - [X | Rest] -> - case Predicate(X) of - true -> - {ok, {X, lists:append(lists:reverse(Checked), Rest)}}; - - false -> - do_pop(Rest, Predicate, [X | Checked]) - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1675). --spec pop(list(AMW), fun((AMW) -> boolean())) -> {ok, {AMW, list(AMW)}} | - {error, nil}. -pop(List, Is_desired) -> - do_pop(List, Is_desired, []). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1682). --spec do_pop_map(list(ANB), fun((ANB) -> {ok, AND} | {error, any()}), list(ANB)) -> {ok, - {AND, list(ANB)}} | - {error, nil}. -do_pop_map(List, Mapper, Checked) -> - case List of - [] -> - {error, nil}; - - [X | Rest] -> - case Mapper(X) of - {ok, Y} -> - {ok, {Y, lists:append(lists:reverse(Checked), Rest)}}; - - {error, _} -> - do_pop_map(Rest, Mapper, [X | Checked]) - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1719). --spec pop_map(list(ANL), fun((ANL) -> {ok, ANN} | {error, any()})) -> {ok, - {ANN, list(ANL)}} | - {error, nil}. -pop_map(Haystack, Is_desired) -> - do_pop_map(Haystack, Is_desired, []). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1749). --spec key_pop(list({ANU, ANV}), ANU) -> {ok, {ANV, list({ANU, ANV})}} | - {error, nil}. -key_pop(List, Key) -> - pop_map( - List, - fun(Entry) -> - {K, V} = Entry, - case K of - K@1 when K@1 =:= Key -> - {ok, V}; - - _ -> - {error, nil} - end - end - ). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1776). --spec key_set(list({AOA, AOB}), AOA, AOB) -> list({AOA, AOB}). -key_set(List, Key, Value) -> - case List of - [] -> - [{Key, Value}]; - - [{K, _} | Rest] when K =:= Key -> - [{Key, Value} | Rest]; - - [First | Rest@1] -> - [First | key_set(Rest@1, Key, Value)] - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1798). --spec each(list(AOE), fun((AOE) -> any())) -> nil. -each(List, F) -> - case List of - [] -> - nil; - - [First | Rest] -> - F(First), - each(Rest, F) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1824). --spec try_each(list(AOH), fun((AOH) -> {ok, any()} | {error, AOK})) -> {ok, nil} | - {error, AOK}. -try_each(List, Fun) -> - case List of - [] -> - {ok, nil}; - - [First | Rest] -> - case Fun(First) of - {ok, _} -> - try_each(Rest, Fun); - - {error, E} -> - {error, E} - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1838). --spec do_partition(list(BHC), fun((BHC) -> boolean()), list(BHC), list(BHC)) -> {list(BHC), - list(BHC)}. -do_partition(List, Categorise, Trues, Falses) -> - case List of - [] -> - {lists:reverse(Trues), lists:reverse(Falses)}; - - [First | Rest] -> - case Categorise(First) of - true -> - do_partition(Rest, Categorise, [First | Trues], Falses); - - false -> - do_partition(Rest, Categorise, Trues, [First | Falses]) - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1861). --spec partition(list(AOU), fun((AOU) -> boolean())) -> {list(AOU), list(AOU)}. -partition(List, Categorise) -> - do_partition(List, Categorise, [], []). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1877). --spec permutations(list(AOY)) -> list(list(AOY)). -permutations(List) -> - case List of - [] -> - [[]]; - - _ -> - _pipe@3 = index_map( - List, - fun(I, I_idx) -> - _pipe = index_fold( - List, - [], - fun(Acc, J, J_idx) -> case I_idx =:= J_idx of - true -> - Acc; - - false -> - [J | Acc] - end end - ), - _pipe@1 = lists:reverse(_pipe), - _pipe@2 = permutations(_pipe@1), - map(_pipe@2, fun(Permutation) -> [I | Permutation] end) - end - ), - flatten(_pipe@3) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1896). --spec do_window(list(list(APC)), list(APC), integer()) -> list(list(APC)). -do_window(Acc, List, N) -> - Window = take(List, N), - case erlang:length(Window) =:= N of - true -> - do_window([Window | Acc], drop(List, 1), N); - - false -> - Acc - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1919). --spec window(list(API), integer()) -> list(list(API)). -window(List, N) -> - case N =< 0 of - true -> - []; - - false -> - _pipe = do_window([], List, N), - lists:reverse(_pipe) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1940). --spec window_by_2(list(APM)) -> list({APM, APM}). -window_by_2(List) -> - zip(List, drop(List, 1)). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1953). --spec drop_while(list(APP), fun((APP) -> boolean())) -> list(APP). -drop_while(List, Predicate) -> - case List of - [] -> - []; - - [First | Rest] -> - case Predicate(First) of - true -> - drop_while(Rest, Predicate); - - false -> - [First | Rest] - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1967). --spec do_take_while(list(APS), fun((APS) -> boolean()), list(APS)) -> list(APS). -do_take_while(List, Predicate, Acc) -> - case List of - [] -> - lists:reverse(Acc); - - [First | Rest] -> - case Predicate(First) of - true -> - do_take_while(Rest, Predicate, [First | Acc]); - - false -> - lists:reverse(Acc) - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1991). --spec take_while(list(APW), fun((APW) -> boolean())) -> list(APW). -take_while(List, Predicate) -> - do_take_while(List, Predicate, []). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 1998). --spec do_chunk(list(APZ), fun((APZ) -> AQB), AQB, list(APZ), list(list(APZ))) -> list(list(APZ)). -do_chunk(List, F, Previous_key, Current_chunk, Acc) -> - case List of - [First | Rest] -> - Key = F(First), - case Key =:= Previous_key of - false -> - New_acc = [lists:reverse(Current_chunk) | Acc], - do_chunk(Rest, F, Key, [First], New_acc); - - _ -> - do_chunk(Rest, F, Key, [First | Current_chunk], Acc) - end; - - _ -> - lists:reverse([lists:reverse(Current_chunk) | Acc]) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 2030). --spec chunk(list(AQH), fun((AQH) -> any())) -> list(list(AQH)). -chunk(List, F) -> - case List of - [] -> - []; - - [First | Rest] -> - do_chunk(Rest, F, F(First), [First], []) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 2037). --spec do_sized_chunk( - list(AQM), - integer(), - integer(), - list(AQM), - list(list(AQM)) -) -> list(list(AQM)). -do_sized_chunk(List, Count, Left, Current_chunk, Acc) -> - case List of - [] -> - case Current_chunk of - [] -> - lists:reverse(Acc); - - Remaining -> - lists:reverse([lists:reverse(Remaining) | Acc]) - end; - - [First | Rest] -> - Chunk = [First | Current_chunk], - case Left > 1 of - false -> - do_sized_chunk( - Rest, - Count, - Count, - [], - [lists:reverse(Chunk) | Acc] - ); - - true -> - do_sized_chunk(Rest, Count, Left - 1, Chunk, Acc) - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 2079). --spec sized_chunk(list(AQT), integer()) -> list(list(AQT)). -sized_chunk(List, Count) -> - do_sized_chunk(List, Count, Count, [], []). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 2103). --spec reduce(list(AQX), fun((AQX, AQX) -> AQX)) -> {ok, AQX} | {error, nil}. -reduce(List, Fun) -> - case List of - [] -> - {error, nil}; - - [First | Rest] -> - {ok, fold(Rest, First, Fun)} - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 2110). --spec do_scan(list(ARB), ARD, list(ARD), fun((ARD, ARB) -> ARD)) -> list(ARD). -do_scan(List, Accumulator, Accumulated, Fun) -> - case List of - [] -> - lists:reverse(Accumulated); - - [First | Rest] -> - Next = Fun(Accumulator, First), - do_scan(Rest, Next, [Next | Accumulated], Fun) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 2134). --spec scan(list(ARG), ARI, fun((ARI, ARG) -> ARI)) -> list(ARI). -scan(List, Initial, Fun) -> - do_scan(List, Initial, [], Fun). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 2162). --spec last(list(ARK)) -> {ok, ARK} | {error, nil}. -last(List) -> - _pipe = List, - reduce(_pipe, fun(_, Elem) -> Elem end). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 2181). --spec combinations(list(ARO), integer()) -> list(list(ARO)). -combinations(Items, N) -> - case N of - 0 -> - [[]]; - - _ -> - case Items of - [] -> - []; - - [First | Rest] -> - First_combinations = begin - _pipe = map( - combinations(Rest, N - 1), - fun(Com) -> [First | Com] end - ), - lists:reverse(_pipe) - end, - fold( - First_combinations, - combinations(Rest, N), - fun(Acc, C) -> [C | Acc] end - ) - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 2199). --spec do_combination_pairs(list(ARS)) -> list(list({ARS, ARS})). -do_combination_pairs(Items) -> - case Items of - [] -> - []; - - [First | Rest] -> - First_combinations = map(Rest, fun(Other) -> {First, Other} end), - [First_combinations | do_combination_pairs(Rest)] - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 2218). --spec combination_pairs(list(ARW)) -> list({ARW, ARW}). -combination_pairs(Items) -> - _pipe = do_combination_pairs(Items), - flatten(_pipe). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 2250). --spec transpose(list(list(ASD))) -> list(list(ASD)). -transpose(List_of_list) -> - Take_first = fun(List) -> case List of - [] -> - []; - - [F] -> - [F]; - - [F@1 | _] -> - [F@1] - end end, - case List_of_list of - [] -> - []; - - [[] | Rest] -> - transpose(Rest); - - Rows -> - Firsts = begin - _pipe = Rows, - _pipe@1 = map(_pipe, Take_first), - flatten(_pipe@1) - end, - Rest@1 = transpose( - map(Rows, fun(_capture) -> drop(_capture, 1) end) - ), - [Firsts | Rest@1] - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 2232). --spec interleave(list(list(ARZ))) -> list(ARZ). -interleave(List) -> - _pipe = transpose(List), - flatten(_pipe). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 2273). --spec do_shuffle_pair_unwrap(list({float(), ASI}), list(ASI)) -> list(ASI). -do_shuffle_pair_unwrap(List, Acc) -> - case List of - [] -> - Acc; - - [Elem_pair | Enumerable] -> - do_shuffle_pair_unwrap( - Enumerable, - [erlang:element(2, Elem_pair) | Acc] - ) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 2281). --spec do_shuffle_by_pair_indexes(list({float(), ASM})) -> list({float(), ASM}). -do_shuffle_by_pair_indexes(List_of_pairs) -> - sort( - List_of_pairs, - fun(A_pair, B_pair) -> - gleam@float:compare( - erlang:element(1, A_pair), - erlang:element(1, B_pair) - ) - end - ). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam", 2300). --spec shuffle(list(ASP)) -> list(ASP). -shuffle(List) -> - _pipe = List, - _pipe@1 = fold(_pipe, [], fun(Acc, A) -> [{rand:uniform(), A} | Acc] end), - _pipe@2 = do_shuffle_by_pair_indexes(_pipe@1), - do_shuffle_pair_unwrap(_pipe@2, []). diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@option.cache b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@option.cache deleted file mode 100644 index fcbd1c38b01..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@option.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@option.cache_meta b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@option.cache_meta deleted file mode 100644 index 98dc30049f5..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@option.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@option.erl b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@option.erl deleted file mode 100644 index e43c4dd9558..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@option.erl +++ /dev/null @@ -1,162 +0,0 @@ --module(gleam@option). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([all/1, is_some/1, is_none/1, to_result/2, from_result/1, unwrap/2, lazy_unwrap/2, map/2, flatten/1, then/2, 'or'/2, lazy_or/2, values/1]). --export_type([option/1]). - --type option(FV) :: {some, FV} | none. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/option.gleam", 24). --spec do_all(list(option(FW)), list(FW)) -> option(list(FW)). -do_all(List, Acc) -> - case List of - [] -> - {some, Acc}; - - [X | Rest] -> - Accumulate = fun(Acc@1, Item) -> case {Acc@1, Item} of - {{some, Values}, {some, Value}} -> - {some, [Value | Values]}; - - {_, _} -> - none - end end, - Accumulate(do_all(Rest, Acc), X) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/option.gleam", 55). --spec all(list(option(GC))) -> option(list(GC)). -all(List) -> - do_all(List, []). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/option.gleam", 73). --spec is_some(option(any())) -> boolean(). -is_some(Option) -> - Option /= none. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/option.gleam", 91). --spec is_none(option(any())) -> boolean(). -is_none(Option) -> - Option =:= none. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/option.gleam", 109). --spec to_result(option(GL), GO) -> {ok, GL} | {error, GO}. -to_result(Option, E) -> - case Option of - {some, A} -> - {ok, A}; - - _ -> - {error, E} - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/option.gleam", 130). --spec from_result({ok, GR} | {error, any()}) -> option(GR). -from_result(Result) -> - case Result of - {ok, A} -> - {some, A}; - - _ -> - none - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/option.gleam", 151). --spec unwrap(option(GW), GW) -> GW. -unwrap(Option, Default) -> - case Option of - {some, X} -> - X; - - none -> - Default - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/option.gleam", 172). --spec lazy_unwrap(option(GY), fun(() -> GY)) -> GY. -lazy_unwrap(Option, Default) -> - case Option of - {some, X} -> - X; - - none -> - Default() - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/option.gleam", 197). --spec map(option(HA), fun((HA) -> HC)) -> option(HC). -map(Option, Fun) -> - case Option of - {some, X} -> - {some, Fun(X)}; - - none -> - none - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/option.gleam", 223). --spec flatten(option(option(HE))) -> option(HE). -flatten(Option) -> - case Option of - {some, X} -> - X; - - none -> - none - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/option.gleam", 262). --spec then(option(HI), fun((HI) -> option(HK))) -> option(HK). -then(Option, Fun) -> - case Option of - {some, X} -> - Fun(X); - - none -> - none - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/option.gleam", 293). --spec 'or'(option(HN), option(HN)) -> option(HN). -'or'(First, Second) -> - case First of - {some, _} -> - First; - - none -> - Second - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/option.gleam", 324). --spec lazy_or(option(HR), fun(() -> option(HR))) -> option(HR). -lazy_or(First, Second) -> - case First of - {some, _} -> - First; - - none -> - Second() - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/option.gleam", 331). --spec do_values(list(option(HV)), list(HV)) -> list(HV). -do_values(List, Acc) -> - case List of - [] -> - Acc; - - [First | Rest] -> - Accumulate = fun(Acc@1, Item) -> case Item of - {some, Value} -> - [Value | Acc@1]; - - none -> - Acc@1 - end end, - Accumulate(do_values(Rest, Acc), First) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/option.gleam", 356). --spec values(list(option(IA))) -> list(IA). -values(Options) -> - do_values(Options, []). diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@order.cache b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@order.cache deleted file mode 100644 index 60ab6d3394a..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@order.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@order.cache_meta b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@order.cache_meta deleted file mode 100644 index 28e9c818294..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@order.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@order.erl b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@order.erl deleted file mode 100644 index 0a91cb79b98..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@order.erl +++ /dev/null @@ -1,85 +0,0 @@ --module(gleam@order). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([negate/1, to_int/1, compare/2, reverse/1, break_tie/2, lazy_break_tie/2]). --export_type([order/0]). - --type order() :: lt | eq | gt. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/order.gleam", 35). --spec negate(order()) -> order(). -negate(Order) -> - case Order of - lt -> - gt; - - eq -> - eq; - - gt -> - lt - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/order.gleam", 62). --spec to_int(order()) -> integer(). -to_int(Order) -> - case Order of - lt -> - -1; - - eq -> - 0; - - gt -> - 1 - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/order.gleam", 79). --spec compare(order(), order()) -> order(). -compare(A, B) -> - case {A, B} of - {X, Y} when X =:= Y -> - eq; - - {lt, _} -> - lt; - - {eq, gt} -> - lt; - - {_, _} -> - gt - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/order.gleam", 100). --spec reverse(fun((I, I) -> order())) -> fun((I, I) -> order()). -reverse(Orderer) -> - fun(A, B) -> Orderer(B, A) end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/order.gleam", 122). --spec break_tie(order(), order()) -> order(). -break_tie(Order, Other) -> - case Order of - lt -> - Order; - - gt -> - Order; - - eq -> - Other - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/order.gleam", 151). --spec lazy_break_tie(order(), fun(() -> order())) -> order(). -lazy_break_tie(Order, Comparison) -> - case Order of - lt -> - Order; - - gt -> - Order; - - eq -> - Comparison() - end. diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@pair.cache b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@pair.cache deleted file mode 100644 index 77f3b0fa02b..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@pair.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@pair.cache_meta b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@pair.cache_meta deleted file mode 100644 index 084e289d3e8..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@pair.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@pair.erl b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@pair.erl deleted file mode 100644 index cf5ec0992a3..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@pair.erl +++ /dev/null @@ -1,39 +0,0 @@ --module(gleam@pair). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([first/1, second/1, swap/1, map_first/2, map_second/2, new/2]). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/pair.gleam", 10). --spec first({YZ, any()}) -> YZ. -first(Pair) -> - {A, _} = Pair, - A. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/pair.gleam", 24). --spec second({any(), AAC}) -> AAC. -second(Pair) -> - {_, A} = Pair, - A. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/pair.gleam", 38). --spec swap({AAD, AAE}) -> {AAE, AAD}. -swap(Pair) -> - {A, B} = Pair, - {B, A}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/pair.gleam", 53). --spec map_first({AAF, AAG}, fun((AAF) -> AAH)) -> {AAH, AAG}. -map_first(Pair, Fun) -> - {A, B} = Pair, - {Fun(A), B}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/pair.gleam", 68). --spec map_second({AAI, AAJ}, fun((AAJ) -> AAK)) -> {AAI, AAK}. -map_second(Pair, Fun) -> - {A, B} = Pair, - {A, Fun(B)}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/pair.gleam", 83). --spec new(AAL, AAM) -> {AAL, AAM}. -new(First, Second) -> - {First, Second}. diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@queue.cache b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@queue.cache deleted file mode 100644 index 66b90f675d3..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@queue.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@queue.cache_meta b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@queue.cache_meta deleted file mode 100644 index ef847119923..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@queue.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@queue.erl b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@queue.erl deleted file mode 100644 index 9d865b94d1c..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@queue.erl +++ /dev/null @@ -1,134 +0,0 @@ --module(gleam@queue). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([new/0, from_list/1, to_list/1, is_empty/1, length/1, push_back/2, push_front/2, pop_back/1, pop_front/1, reverse/1, is_logically_equal/3, is_equal/2]). --export_type([queue/1]). - --opaque queue(EXI) :: {queue, list(EXI), list(EXI)}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/queue.gleam", 22). --spec new() -> queue(any()). -new() -> - {queue, [], []}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/queue.gleam", 38). --spec from_list(list(EXL)) -> queue(EXL). -from_list(List) -> - {queue, [], List}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/queue.gleam", 54). --spec to_list(queue(EXO)) -> list(EXO). -to_list(Queue) -> - _pipe = erlang:element(3, Queue), - lists:append(_pipe, lists:reverse(erlang:element(2, Queue))). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/queue.gleam", 80). --spec is_empty(queue(any())) -> boolean(). -is_empty(Queue) -> - (erlang:element(2, Queue) =:= []) andalso (erlang:element(3, Queue) =:= []). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/queue.gleam", 106). --spec length(queue(any())) -> integer(). -length(Queue) -> - erlang:length(erlang:element(2, Queue)) + erlang:length( - erlang:element(3, Queue) - ). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/queue.gleam", 119). --spec push_back(queue(EXV), EXV) -> queue(EXV). -push_back(Queue, Item) -> - {queue, [Item | erlang:element(2, Queue)], erlang:element(3, Queue)}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/queue.gleam", 132). --spec push_front(queue(EXY), EXY) -> queue(EXY). -push_front(Queue, Item) -> - {queue, erlang:element(2, Queue), [Item | erlang:element(3, Queue)]}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/queue.gleam", 164). --spec pop_back(queue(EYB)) -> {ok, {EYB, queue(EYB)}} | {error, nil}. -pop_back(Queue) -> - case Queue of - {queue, [], []} -> - {error, nil}; - - {queue, [], Out} -> - pop_back({queue, lists:reverse(Out), []}); - - {queue, [First | Rest], Out@1} -> - Queue@1 = {queue, Rest, Out@1}, - {ok, {First, Queue@1}} - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/queue.gleam", 203). --spec pop_front(queue(EYG)) -> {ok, {EYG, queue(EYG)}} | {error, nil}. -pop_front(Queue) -> - case Queue of - {queue, [], []} -> - {error, nil}; - - {queue, In, []} -> - pop_front({queue, [], lists:reverse(In)}); - - {queue, In@1, [First | Rest]} -> - Queue@1 = {queue, In@1, Rest}, - {ok, {First, Queue@1}} - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/queue.gleam", 236). --spec reverse(queue(EYL)) -> queue(EYL). -reverse(Queue) -> - {queue, erlang:element(3, Queue), erlang:element(2, Queue)}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/queue.gleam", 240). --spec check_equal( - list(EYO), - list(EYO), - list(EYO), - list(EYO), - fun((EYO, EYO) -> boolean()) -) -> boolean(). -check_equal(Xs, X_tail, Ys, Y_tail, Eq) -> - case {Xs, X_tail, Ys, Y_tail} of - {[], [], [], []} -> - true; - - {[X | Xs@1], _, [Y | Ys@1], _} -> - case Eq(X, Y) of - false -> - false; - - true -> - check_equal(Xs@1, X_tail, Ys@1, Y_tail, Eq) - end; - - {[], [_ | _], _, _} -> - check_equal(lists:reverse(X_tail), [], Ys, Y_tail, Eq); - - {_, _, [], [_ | _]} -> - check_equal(Xs, X_tail, lists:reverse(Y_tail), [], Eq); - - {_, _, _, _} -> - false - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/queue.gleam", 271). --spec is_logically_equal(queue(EYT), queue(EYT), fun((EYT, EYT) -> boolean())) -> boolean(). -is_logically_equal(A, B, Element_is_equal) -> - check_equal( - erlang:element(3, A), - erlang:element(2, A), - erlang:element(3, B), - erlang:element(2, B), - Element_is_equal - ). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/queue.gleam", 288). --spec is_equal(queue(EYW), queue(EYW)) -> boolean(). -is_equal(A, B) -> - check_equal( - erlang:element(3, A), - erlang:element(2, A), - erlang:element(3, B), - erlang:element(2, B), - fun(A@1, B@1) -> A@1 =:= B@1 end - ). diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@regex.cache b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@regex.cache deleted file mode 100644 index a4a303b9f77..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@regex.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@regex.cache_meta b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@regex.cache_meta deleted file mode 100644 index 3dcdb710cd7..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@regex.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@regex.erl b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@regex.erl deleted file mode 100644 index 0630b8567d2..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@regex.erl +++ /dev/null @@ -1,43 +0,0 @@ --module(gleam@regex). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([compile/2, from_string/1, check/2, split/2, scan/2, replace/3]). --export_type([regex/0, match/0, compile_error/0, options/0]). - --type regex() :: any(). - --type match() :: {match, binary(), list(gleam@option:option(binary()))}. - --type compile_error() :: {compile_error, binary(), integer()}. - --type options() :: {options, boolean(), boolean()}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/regex.gleam", 55). --spec compile(binary(), options()) -> {ok, regex()} | {error, compile_error()}. -compile(Pattern, Options) -> - gleam_stdlib:compile_regex(Pattern, Options). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/regex.gleam", 92). --spec from_string(binary()) -> {ok, regex()} | {error, compile_error()}. -from_string(Pattern) -> - compile(Pattern, {options, false, false}). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/regex.gleam", 111). --spec check(regex(), binary()) -> boolean(). -check(Regex, String) -> - gleam_stdlib:regex_check(Regex, String). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/regex.gleam", 129). --spec split(regex(), binary()) -> list(binary()). -split(Regex, String) -> - gleam_stdlib:regex_split(Regex, String). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/regex.gleam", 189). --spec scan(regex(), binary()) -> list(match()). -scan(Regex, String) -> - gleam_stdlib:regex_scan(Regex, String). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/regex.gleam", 215). --spec replace(regex(), binary(), binary()) -> binary(). -replace(Pattern, String, Substitute) -> - gleam_stdlib:regex_replace(Pattern, String, Substitute). diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@result.cache b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@result.cache deleted file mode 100644 index d489c24e286..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@result.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@result.cache_meta b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@result.cache_meta deleted file mode 100644 index d8284f39a35..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@result.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@result.erl b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@result.erl deleted file mode 100644 index 742ee0459e2..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@result.erl +++ /dev/null @@ -1,222 +0,0 @@ --module(gleam@result). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([is_ok/1, is_error/1, map/2, map_error/2, flatten/1, 'try'/2, then/2, unwrap/2, lazy_unwrap/2, unwrap_error/2, unwrap_both/1, nil_error/1, 'or'/2, lazy_or/2, all/1, partition/1, replace/2, replace_error/2, values/1, try_recover/2]). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/result.gleam", 20). --spec is_ok({ok, any()} | {error, any()}) -> boolean(). -is_ok(Result) -> - case Result of - {error, _} -> - false; - - {ok, _} -> - true - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/result.gleam", 41). --spec is_error({ok, any()} | {error, any()}) -> boolean(). -is_error(Result) -> - case Result of - {ok, _} -> - false; - - {error, _} -> - true - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/result.gleam", 66). --spec map({ok, BXE} | {error, BXF}, fun((BXE) -> BXI)) -> {ok, BXI} | - {error, BXF}. -map(Result, Fun) -> - case Result of - {ok, X} -> - {ok, Fun(X)}; - - {error, E} -> - {error, E} - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/result.gleam", 91). --spec map_error({ok, BXL} | {error, BXM}, fun((BXM) -> BXP)) -> {ok, BXL} | - {error, BXP}. -map_error(Result, Fun) -> - case Result of - {ok, X} -> - {ok, X}; - - {error, Error} -> - {error, Fun(Error)} - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/result.gleam", 120). --spec flatten({ok, {ok, BXS} | {error, BXT}} | {error, BXT}) -> {ok, BXS} | - {error, BXT}. -flatten(Result) -> - case Result of - {ok, X} -> - X; - - {error, Error} -> - {error, Error} - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/result.gleam", 158). --spec 'try'({ok, BYA} | {error, BYB}, fun((BYA) -> {ok, BYE} | {error, BYB})) -> {ok, - BYE} | - {error, BYB}. -'try'(Result, Fun) -> - case Result of - {ok, X} -> - Fun(X); - - {error, E} -> - {error, E} - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/result.gleam", 170). --spec then({ok, BYJ} | {error, BYK}, fun((BYJ) -> {ok, BYN} | {error, BYK})) -> {ok, - BYN} | - {error, BYK}. -then(Result, Fun) -> - 'try'(Result, Fun). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/result.gleam", 192). --spec unwrap({ok, BYS} | {error, any()}, BYS) -> BYS. -unwrap(Result, Default) -> - case Result of - {ok, V} -> - V; - - {error, _} -> - Default - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/result.gleam", 214). --spec lazy_unwrap({ok, BYW} | {error, any()}, fun(() -> BYW)) -> BYW. -lazy_unwrap(Result, Default) -> - case Result of - {ok, V} -> - V; - - {error, _} -> - Default() - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/result.gleam", 236). --spec unwrap_error({ok, any()} | {error, BZB}, BZB) -> BZB. -unwrap_error(Result, Default) -> - case Result of - {ok, _} -> - Default; - - {error, E} -> - E - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/result.gleam", 258). --spec unwrap_both({ok, BZE} | {error, BZE}) -> BZE. -unwrap_both(Result) -> - case Result of - {ok, A} -> - A; - - {error, A@1} -> - A@1 - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/result.gleam", 279). --spec nil_error({ok, BZH} | {error, any()}) -> {ok, BZH} | {error, nil}. -nil_error(Result) -> - map_error(Result, fun(_) -> nil end). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/result.gleam", 307). --spec 'or'({ok, BZN} | {error, BZO}, {ok, BZN} | {error, BZO}) -> {ok, BZN} | - {error, BZO}. -'or'(First, Second) -> - case First of - {ok, _} -> - First; - - {error, _} -> - Second - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/result.gleam", 340). --spec lazy_or({ok, BZV} | {error, BZW}, fun(() -> {ok, BZV} | {error, BZW})) -> {ok, - BZV} | - {error, BZW}. -lazy_or(First, Second) -> - case First of - {ok, _} -> - First; - - {error, _} -> - Second() - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/result.gleam", 366). --spec all(list({ok, CAD} | {error, CAE})) -> {ok, list(CAD)} | {error, CAE}. -all(Results) -> - gleam@list:try_map(Results, fun(X) -> X end). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/result.gleam", 386). --spec do_partition(list({ok, CAS} | {error, CAT}), list(CAS), list(CAT)) -> {list(CAS), - list(CAT)}. -do_partition(Results, Oks, Errors) -> - case Results of - [] -> - {Oks, Errors}; - - [{ok, A} | Rest] -> - do_partition(Rest, [A | Oks], Errors); - - [{error, E} | Rest@1] -> - do_partition(Rest@1, Oks, [E | Errors]) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/result.gleam", 382). --spec partition(list({ok, CAL} | {error, CAM})) -> {list(CAL), list(CAM)}. -partition(Results) -> - do_partition(Results, [], []). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/result.gleam", 408). --spec replace({ok, any()} | {error, CBB}, CBE) -> {ok, CBE} | {error, CBB}. -replace(Result, Value) -> - case Result of - {ok, _} -> - {ok, Value}; - - {error, Error} -> - {error, Error} - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/result.gleam", 429). --spec replace_error({ok, CBH} | {error, any()}, CBL) -> {ok, CBH} | {error, CBL}. -replace_error(Result, Error) -> - case Result of - {ok, X} -> - {ok, X}; - - {error, _} -> - {error, Error} - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/result.gleam", 445). --spec values(list({ok, CBO} | {error, any()})) -> list(CBO). -values(Results) -> - gleam@list:filter_map(Results, fun(R) -> R end). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/result.gleam", 478). --spec try_recover( - {ok, CBU} | {error, CBV}, - fun((CBV) -> {ok, CBU} | {error, CBY}) -) -> {ok, CBU} | {error, CBY}. -try_recover(Result, Fun) -> - case Result of - {ok, Value} -> - {ok, Value}; - - {error, Error} -> - Fun(Error) - end. diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@set.cache b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@set.cache deleted file mode 100644 index 3b821c6af90..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@set.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@set.cache_meta b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@set.cache_meta deleted file mode 100644 index 14a143061a9..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@set.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@set.erl b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@set.erl deleted file mode 100644 index 176430a8cc6..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@set.erl +++ /dev/null @@ -1,141 +0,0 @@ --module(gleam@set). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([new/0, size/1, is_empty/1, contains/2, delete/2, to_list/1, fold/3, filter/2, drop/2, take/2, intersection/2, difference/2, is_subset/2, is_disjoint/2, each/2, insert/2, from_list/1, map/2, union/2, symmetric_difference/2]). --export_type([set/1]). - --opaque set(FCQ) :: {set, gleam@dict:dict(FCQ, list(nil))}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/set.gleam", 32). --spec new() -> set(any()). -new() -> - {set, gleam@dict:new()}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/set.gleam", 50). --spec size(set(any())) -> integer(). -size(Set) -> - maps:size(erlang:element(2, Set)). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/set.gleam", 68). --spec is_empty(set(any())) -> boolean(). -is_empty(Set) -> - Set =:= new(). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/set.gleam", 110). --spec contains(set(FDB), FDB) -> boolean(). -contains(Set, Member) -> - _pipe = erlang:element(2, Set), - _pipe@1 = gleam@dict:get(_pipe, Member), - gleam@result:is_ok(_pipe@1). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/set.gleam", 131). --spec delete(set(FDD), FDD) -> set(FDD). -delete(Set, Member) -> - {set, gleam@dict:delete(erlang:element(2, Set), Member)}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/set.gleam", 149). --spec to_list(set(FDG)) -> list(FDG). -to_list(Set) -> - gleam@dict:keys(erlang:element(2, Set)). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/set.gleam", 190). --spec fold(set(FDM), FDO, fun((FDO, FDM) -> FDO)) -> FDO. -fold(Set, Initial, Reducer) -> - gleam@dict:fold( - erlang:element(2, Set), - Initial, - fun(A, K, _) -> Reducer(A, K) end - ). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/set.gleam", 214). --spec filter(set(FDP), fun((FDP) -> boolean())) -> set(FDP). -filter(Set, Predicate) -> - {set, - gleam@dict:filter(erlang:element(2, Set), fun(M, _) -> Predicate(M) end)}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/set.gleam", 249). --spec drop(set(FDW), list(FDW)) -> set(FDW). -drop(Set, Disallowed) -> - gleam@list:fold(Disallowed, Set, fun delete/2). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/set.gleam", 267). --spec take(set(FEA), list(FEA)) -> set(FEA). -take(Set, Desired) -> - {set, gleam@dict:take(erlang:element(2, Set), Desired)}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/set.gleam", 271). --spec order(set(FEE), set(FEE)) -> {set(FEE), set(FEE)}. -order(First, Second) -> - case maps:size(erlang:element(2, First)) > maps:size( - erlang:element(2, Second) - ) of - true -> - {First, Second}; - - false -> - {Second, First} - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/set.gleam", 305). --spec intersection(set(FEN), set(FEN)) -> set(FEN). -intersection(First, Second) -> - {Larger, Smaller} = order(First, Second), - take(Larger, to_list(Smaller)). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/set.gleam", 323). --spec difference(set(FER), set(FER)) -> set(FER). -difference(First, Second) -> - drop(First, to_list(Second)). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/set.gleam", 344). --spec is_subset(set(FEV), set(FEV)) -> boolean(). -is_subset(First, Second) -> - intersection(First, Second) =:= First. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/set.gleam", 362). --spec is_disjoint(set(FEY), set(FEY)) -> boolean(). -is_disjoint(First, Second) -> - intersection(First, Second) =:= new(). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/set.gleam", 402). --spec each(set(FFF), fun((FFF) -> any())) -> nil. -each(Set, Fun) -> - fold( - Set, - nil, - fun(Nil, Member) -> - Fun(Member), - Nil - end - ). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/set.gleam", 86). --spec insert(set(FCY), FCY) -> set(FCY). -insert(Set, Member) -> - {set, gleam@dict:insert(erlang:element(2, Set), Member, [])}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/set.gleam", 167). --spec from_list(list(FDJ)) -> set(FDJ). -from_list(Members) -> - Dict = gleam@list:fold( - Members, - gleam@dict:new(), - fun(M, K) -> gleam@dict:insert(M, K, []) end - ), - {set, Dict}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/set.gleam", 232). --spec map(set(FDS), fun((FDS) -> FDU)) -> set(FDU). -map(Set, Fun) -> - fold(Set, new(), fun(Acc, Member) -> insert(Acc, Fun(Member)) end). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/set.gleam", 289). --spec union(set(FEJ), set(FEJ)) -> set(FEJ). -union(First, Second) -> - {Larger, Smaller} = order(First, Second), - fold(Smaller, Larger, fun insert/2). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/set.gleam", 374). --spec symmetric_difference(set(FFB), set(FFB)) -> set(FFB). -symmetric_difference(First, Second) -> - difference(union(First, Second), intersection(First, Second)). diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@string.cache b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@string.cache deleted file mode 100644 index 98ca120fe56..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@string.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@string.cache_meta b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@string.cache_meta deleted file mode 100644 index 86962e061b7..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@string.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@string.erl b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@string.erl deleted file mode 100644 index f05946bce45..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@string.erl +++ /dev/null @@ -1,409 +0,0 @@ --module(gleam@string). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([is_empty/1, length/1, reverse/1, replace/3, lowercase/1, uppercase/1, compare/2, slice/3, crop/2, drop_left/2, drop_right/2, contains/2, starts_with/2, ends_with/2, split_once/2, append/2, concat/1, repeat/2, join/2, pad_left/3, pad_right/3, trim/1, trim_left/1, trim_right/1, pop_grapheme/1, to_graphemes/1, split/2, to_utf_codepoints/1, from_utf_codepoints/1, utf_codepoint/1, utf_codepoint_to_int/1, to_option/1, first/1, last/1, capitalise/1, inspect/1, byte_size/1]). --export_type([direction/0]). - --type direction() :: leading | trailing | both. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 23). --spec is_empty(binary()) -> boolean(). -is_empty(Str) -> - Str =:= <<""/utf8>>. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 49). --spec length(binary()) -> integer(). -length(String) -> - string:length(String). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 73). --spec do_reverse(binary()) -> binary(). -do_reverse(String) -> - _pipe = String, - _pipe@1 = gleam@string_builder:from_string(_pipe), - _pipe@2 = gleam@string_builder:reverse(_pipe@1), - gleam@string_builder:to_string(_pipe@2). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 69). --spec reverse(binary()) -> binary(). -reverse(String) -> - do_reverse(String). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 94). --spec replace(binary(), binary(), binary()) -> binary(). -replace(String, Pattern, Substitute) -> - _pipe = String, - _pipe@1 = gleam@string_builder:from_string(_pipe), - _pipe@2 = gleam_stdlib:string_replace(_pipe@1, Pattern, Substitute), - gleam@string_builder:to_string(_pipe@2). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 117). --spec lowercase(binary()) -> binary(). -lowercase(String) -> - string:lowercase(String). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 137). --spec uppercase(binary()) -> binary(). -uppercase(String) -> - string:uppercase(String). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 161). --spec compare(binary(), binary()) -> gleam@order:order(). -compare(A, B) -> - case A =:= B of - true -> - eq; - - _ -> - case gleam_stdlib:less_than(A, B) of - true -> - lt; - - _ -> - gt - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 206). --spec slice(binary(), integer(), integer()) -> binary(). -slice(String, Idx, Len) -> - case Len < 0 of - true -> - <<""/utf8>>; - - false -> - case Idx < 0 of - true -> - Translated_idx = length(String) + Idx, - case Translated_idx < 0 of - true -> - <<""/utf8>>; - - false -> - gleam_stdlib:slice(String, Translated_idx, Len) - end; - - false -> - gleam_stdlib:slice(String, Idx, Len) - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 239). --spec crop(binary(), binary()) -> binary(). -crop(String, Substring) -> - gleam_stdlib:crop_string(String, Substring). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 250). --spec drop_left(binary(), integer()) -> binary(). -drop_left(String, Num_graphemes) -> - case Num_graphemes < 0 of - true -> - String; - - false -> - slice(String, Num_graphemes, length(String) - Num_graphemes) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 266). --spec drop_right(binary(), integer()) -> binary(). -drop_right(String, Num_graphemes) -> - case Num_graphemes < 0 of - true -> - String; - - false -> - slice(String, 0, length(String) - Num_graphemes) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 294). --spec contains(binary(), binary()) -> boolean(). -contains(Haystack, Needle) -> - gleam_stdlib:contains_string(Haystack, Needle). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 305). --spec starts_with(binary(), binary()) -> boolean(). -starts_with(String, Prefix) -> - gleam_stdlib:string_starts_with(String, Prefix). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 322). --spec ends_with(binary(), binary()) -> boolean(). -ends_with(String, Suffix) -> - gleam_stdlib:string_ends_with(String, Suffix). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 374). --spec do_split_once(binary(), binary()) -> {ok, {binary(), binary()}} | - {error, nil}. -do_split_once(String, Substring) -> - case string:split(String, Substring) of - [First, Rest] -> - {ok, {First, Rest}}; - - _ -> - {error, nil} - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 366). --spec split_once(binary(), binary()) -> {ok, {binary(), binary()}} | - {error, nil}. -split_once(String, Substring) -> - do_split_once(String, Substring). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 400). --spec append(binary(), binary()) -> binary(). -append(First, Second) -> - _pipe = First, - _pipe@1 = gleam@string_builder:from_string(_pipe), - _pipe@2 = gleam@string_builder:append(_pipe@1, Second), - gleam@string_builder:to_string(_pipe@2). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 420). --spec concat(list(binary())) -> binary(). -concat(Strings) -> - _pipe = Strings, - _pipe@1 = gleam@string_builder:from_strings(_pipe), - gleam@string_builder:to_string(_pipe@1). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 441). --spec do_repeat(binary(), integer(), binary()) -> binary(). -do_repeat(String, Times, Acc) -> - case Times =< 0 of - true -> - Acc; - - false -> - do_repeat(String, Times - 1, <>) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 437). --spec repeat(binary(), integer()) -> binary(). -repeat(String, Times) -> - do_repeat(String, Times, <<""/utf8>>). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 464). --spec do_join(list(binary()), binary()) -> binary(). -do_join(Strings, Separator) -> - _pipe = Strings, - _pipe@1 = gleam@list:intersperse(_pipe, Separator), - concat(_pipe@1). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 459). --spec join(list(binary()), binary()) -> binary(). -join(Strings, Separator) -> - do_join(Strings, Separator). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 536). --spec padding(integer(), binary()) -> binary(). -padding(Size, Pad_string) -> - Pad_string_length = length(Pad_string), - Num_pads = case Pad_string_length of - 0 -> 0; - Gleam@denominator -> Size div Gleam@denominator - end, - Extra = case Pad_string_length of - 0 -> 0; - Gleam@denominator@1 -> Size rem Gleam@denominator@1 - end, - <<(repeat(Pad_string, Num_pads))/binary, - (slice(Pad_string, 0, Extra))/binary>>. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 489). --spec pad_left(binary(), integer(), binary()) -> binary(). -pad_left(String, Desired_length, Pad_string) -> - Current_length = length(String), - To_pad_length = Desired_length - Current_length, - case To_pad_length =< 0 of - true -> - String; - - false -> - <<(padding(To_pad_length, Pad_string))/binary, String/binary>> - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 522). --spec pad_right(binary(), integer(), binary()) -> binary(). -pad_right(String, Desired_length, Pad_string) -> - Current_length = length(String), - To_pad_length = Desired_length - Current_length, - case To_pad_length =< 0 of - true -> - String; - - false -> - <> - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 558). --spec do_trim(binary()) -> binary(). -do_trim(String) -> - string:trim(String, both). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 553). --spec trim(binary()) -> binary(). -trim(String) -> - do_trim(String). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 585). --spec do_trim_left(binary()) -> binary(). -do_trim_left(String) -> - string:trim(String, leading). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 580). --spec trim_left(binary()) -> binary(). -trim_left(String) -> - do_trim_left(String). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 603). --spec do_trim_right(binary()) -> binary(). -do_trim_right(String) -> - string:trim(String, trailing). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 598). --spec trim_right(binary()) -> binary(). -trim_right(String) -> - do_trim_right(String). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 626). --spec pop_grapheme(binary()) -> {ok, {binary(), binary()}} | {error, nil}. -pop_grapheme(String) -> - gleam_stdlib:string_pop_grapheme(String). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 648). --spec do_to_graphemes(binary(), list(binary())) -> list(binary()). -do_to_graphemes(String, Acc) -> - case pop_grapheme(String) of - {ok, {Grapheme, Rest}} -> - do_to_graphemes(Rest, [Grapheme | Acc]); - - _ -> - Acc - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 643). --spec to_graphemes(binary()) -> list(binary()). -to_graphemes(String) -> - _pipe = do_to_graphemes(String, []), - lists:reverse(_pipe). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 339). --spec split(binary(), binary()) -> list(binary()). -split(X, Substring) -> - case Substring of - <<""/utf8>> -> - to_graphemes(X); - - _ -> - _pipe = X, - _pipe@1 = gleam@string_builder:from_string(_pipe), - _pipe@2 = gleam@string_builder:split(_pipe@1, Substring), - gleam@list:map(_pipe@2, fun gleam@string_builder:to_string/1) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 696). --spec do_to_utf_codepoints_impl(bitstring(), list(integer())) -> list(integer()). -do_to_utf_codepoints_impl(Bit_array, Acc) -> - case Bit_array of - <> -> - do_to_utf_codepoints_impl(Rest, [First | Acc]); - - _ -> - Acc - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 690). --spec do_to_utf_codepoints(binary()) -> list(integer()). -do_to_utf_codepoints(String) -> - _pipe = do_to_utf_codepoints_impl(<>, []), - lists:reverse(_pipe). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 685). --spec to_utf_codepoints(binary()) -> list(integer()). -to_utf_codepoints(String) -> - do_to_utf_codepoints(String). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 736). --spec from_utf_codepoints(list(integer())) -> binary(). -from_utf_codepoints(Utf_codepoints) -> - gleam_stdlib:utf_codepoint_list_to_string(Utf_codepoints). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 742). --spec utf_codepoint(integer()) -> {ok, integer()} | {error, nil}. -utf_codepoint(Value) -> - case Value of - I when I > 1114111 -> - {error, nil}; - - 65534 -> - {error, nil}; - - 65535 -> - {error, nil}; - - I@1 when (I@1 >= 55296) andalso (I@1 =< 57343) -> - {error, nil}; - - I@2 -> - {ok, gleam_stdlib:identity(I@2)} - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 761). --spec utf_codepoint_to_int(integer()) -> integer(). -utf_codepoint_to_int(Cp) -> - gleam_stdlib:identity(Cp). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 784). --spec to_option(binary()) -> gleam@option:option(binary()). -to_option(String) -> - case String of - <<""/utf8>> -> - none; - - _ -> - {some, String} - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 807). --spec first(binary()) -> {ok, binary()} | {error, nil}. -first(String) -> - case pop_grapheme(String) of - {ok, {First, _}} -> - {ok, First}; - - {error, E} -> - {error, E} - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 830). --spec last(binary()) -> {ok, binary()} | {error, nil}. -last(String) -> - case pop_grapheme(String) of - {ok, {First, <<""/utf8>>}} -> - {ok, First}; - - {ok, {_, Rest}} -> - {ok, slice(Rest, -1, 1)}; - - {error, E} -> - {error, E} - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 848). --spec capitalise(binary()) -> binary(). -capitalise(String) -> - case pop_grapheme(String) of - {ok, {First, Rest}} -> - append(uppercase(First), lowercase(Rest)); - - _ -> - <<""/utf8>> - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 857). --spec inspect(any()) -> binary(). -inspect(Term) -> - _pipe = gleam_stdlib:inspect(Term), - gleam@string_builder:to_string(_pipe). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam", 880). --spec byte_size(binary()) -> integer(). -byte_size(String) -> - erlang:byte_size(String). diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@string_builder.cache b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@string_builder.cache deleted file mode 100644 index 19f296b2569..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@string_builder.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@string_builder.cache_meta b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@string_builder.cache_meta deleted file mode 100644 index 72cc7bc898e..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@string_builder.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@string_builder.erl b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@string_builder.erl deleted file mode 100644 index c0669fd3817..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@string_builder.erl +++ /dev/null @@ -1,106 +0,0 @@ --module(gleam@string_builder). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([prepend_builder/2, append_builder/2, new/0, from_strings/1, concat/1, from_string/1, prepend/2, append/2, to_string/1, byte_size/1, join/2, lowercase/1, uppercase/1, reverse/1, split/2, replace/3, is_equal/2, is_empty/1]). --export_type([string_builder/0, direction/0]). - --type string_builder() :: any(). - --type direction() :: all. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string_builder.gleam", 51). --spec prepend_builder(string_builder(), string_builder()) -> string_builder(). -prepend_builder(Builder, Prefix) -> - gleam_stdlib:iodata_append(Prefix, Builder). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string_builder.gleam", 62). --spec append_builder(string_builder(), string_builder()) -> string_builder(). -append_builder(Builder, Suffix) -> - gleam_stdlib:iodata_append(Builder, Suffix). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string_builder.gleam", 24). --spec new() -> string_builder(). -new() -> - gleam_stdlib:identity([]). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string_builder.gleam", 77). --spec from_strings(list(binary())) -> string_builder(). -from_strings(Strings) -> - gleam_stdlib:identity(Strings). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string_builder.gleam", 89). --spec concat(list(string_builder())) -> string_builder(). -concat(Builders) -> - gleam_stdlib:identity(Builders). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string_builder.gleam", 101). --spec from_string(binary()) -> string_builder(). -from_string(String) -> - gleam_stdlib:identity(String). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string_builder.gleam", 32). --spec prepend(string_builder(), binary()) -> string_builder(). -prepend(Builder, Prefix) -> - append_builder(from_string(Prefix), Builder). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string_builder.gleam", 43). --spec append(string_builder(), binary()) -> string_builder(). -append(Builder, Second) -> - append_builder(Builder, from_string(Second)). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string_builder.gleam", 114). --spec to_string(string_builder()) -> binary(). -to_string(Builder) -> - unicode:characters_to_binary(Builder). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string_builder.gleam", 124). --spec byte_size(string_builder()) -> integer(). -byte_size(Builder) -> - erlang:iolist_size(Builder). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string_builder.gleam", 134). --spec join(list(string_builder()), binary()) -> string_builder(). -join(Builders, Sep) -> - _pipe = Builders, - _pipe@1 = gleam@list:intersperse(_pipe, from_string(Sep)), - concat(_pipe@1). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string_builder.gleam", 143). --spec lowercase(string_builder()) -> string_builder(). -lowercase(Builder) -> - string:lowercase(Builder). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string_builder.gleam", 154). --spec uppercase(string_builder()) -> string_builder(). -uppercase(Builder) -> - string:uppercase(Builder). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string_builder.gleam", 164). --spec reverse(string_builder()) -> string_builder(). -reverse(Builder) -> - string:reverse(Builder). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string_builder.gleam", 191). --spec do_split(string_builder(), binary()) -> list(string_builder()). -do_split(Iodata, Pattern) -> - string:split(Iodata, Pattern, all). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string_builder.gleam", 182). --spec split(string_builder(), binary()) -> list(string_builder()). -split(Iodata, Pattern) -> - do_split(Iodata, Pattern). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string_builder.gleam", 202). --spec replace(string_builder(), binary(), binary()) -> string_builder(). -replace(Builder, Pattern, Substitute) -> - gleam_stdlib:string_replace(Builder, Pattern, Substitute). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string_builder.gleam", 227). --spec is_equal(string_builder(), string_builder()) -> boolean(). -is_equal(A, B) -> - string:equal(A, B). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string_builder.gleam", 251). --spec is_empty(string_builder()) -> boolean(). -is_empty(Builder) -> - string:is_empty(Builder). diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@uri.cache b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@uri.cache deleted file mode 100644 index cd27f460dbd..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@uri.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@uri.cache_meta b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@uri.cache_meta deleted file mode 100644 index e5d8208db9a..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@uri.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@uri.erl b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@uri.erl deleted file mode 100644 index 8c567f133cb..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam@uri.erl +++ /dev/null @@ -1,376 +0,0 @@ --module(gleam@uri). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([parse/1, parse_query/1, percent_encode/1, query_to_string/1, percent_decode/1, path_segments/1, to_string/1, origin/1, merge/2]). --export_type([uri/0]). - --type uri() :: {uri, - gleam@option:option(binary()), - gleam@option:option(binary()), - gleam@option:option(binary()), - gleam@option:option(integer()), - binary(), - gleam@option:option(binary()), - gleam@option:option(binary())}. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/uri.gleam", 116). --spec regex_submatches(binary(), binary()) -> list(gleam@option:option(binary())). -regex_submatches(Pattern, String) -> - _pipe = Pattern, - _pipe@1 = gleam@regex:compile(_pipe, {options, true, false}), - _pipe@2 = gleam@result:nil_error(_pipe@1), - _pipe@3 = gleam@result:map( - _pipe@2, - fun(_capture) -> gleam@regex:scan(_capture, String) end - ), - _pipe@4 = gleam@result:'try'(_pipe@3, fun gleam@list:first/1), - _pipe@5 = gleam@result:map(_pipe@4, fun(M) -> erlang:element(3, M) end), - gleam@result:unwrap(_pipe@5, []). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/uri.gleam", 126). --spec noneify_query(gleam@option:option(binary())) -> gleam@option:option(binary()). -noneify_query(X) -> - case X of - none -> - none; - - {some, X@1} -> - case gleam@string:pop_grapheme(X@1) of - {ok, {<<"?"/utf8>>, Query}} -> - {some, Query}; - - _ -> - none - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/uri.gleam", 137). --spec noneify_empty_string(gleam@option:option(binary())) -> gleam@option:option(binary()). -noneify_empty_string(X) -> - case X of - {some, <<""/utf8>>} -> - none; - - none -> - none; - - {some, _} -> - X - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/uri.gleam", 178). --spec extra_required(list(any()), integer()) -> integer(). -extra_required(List, Remaining) -> - case List of - _ when Remaining =:= 0 -> - 0; - - [] -> - Remaining; - - [_ | Rest] -> - extra_required(Rest, Remaining - 1) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/uri.gleam", 173). --spec pad_list(list(gleam@option:option(FJL)), integer()) -> list(gleam@option:option(FJL)). -pad_list(List, Size) -> - _pipe = List, - lists:append(_pipe, gleam@list:repeat(none, extra_required(List, Size))). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/uri.gleam", 145). --spec split_authority(gleam@option:option(binary())) -> {gleam@option:option(binary()), - gleam@option:option(binary()), - gleam@option:option(integer())}. -split_authority(Authority) -> - case gleam@option:unwrap(Authority, <<""/utf8>>) of - <<""/utf8>> -> - {none, none, none}; - - <<"//"/utf8>> -> - {none, {some, <<""/utf8>>}, none}; - - Authority@1 -> - Matches = begin - _pipe = <<"^(//)?((.*)@)?(\\[[a-zA-Z0-9:.]*\\]|[^:]*)(:(\\d*))?"/utf8>>, - _pipe@1 = regex_submatches(_pipe, Authority@1), - pad_list(_pipe@1, 6) - end, - case Matches of - [_, _, Userinfo, Host, _, Port] -> - Userinfo@1 = noneify_empty_string(Userinfo), - Host@1 = noneify_empty_string(Host), - Port@1 = begin - _pipe@2 = Port, - _pipe@3 = gleam@option:unwrap(_pipe@2, <<""/utf8>>), - _pipe@4 = gleam@int:parse(_pipe@3), - gleam@option:from_result(_pipe@4) - end, - {Userinfo@1, Host@1, Port@1}; - - _ -> - {none, none, none} - end - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/uri.gleam", 56). --spec parse(binary()) -> {ok, uri()} | {error, nil}. -parse(Uri_string) -> - gleam_stdlib:uri_parse(Uri_string). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/uri.gleam", 198). --spec parse_query(binary()) -> {ok, list({binary(), binary()})} | {error, nil}. -parse_query(Query) -> - gleam_stdlib:parse_query(Query). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/uri.gleam", 242). --spec percent_encode(binary()) -> binary(). -percent_encode(Value) -> - gleam_stdlib:percent_encode(Value). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/uri.gleam", 225). --spec query_pair({binary(), binary()}) -> gleam@string_builder:string_builder(). -query_pair(Pair) -> - gleam@string_builder:from_strings( - [percent_encode(erlang:element(1, Pair)), - <<"="/utf8>>, - percent_encode(erlang:element(2, Pair))] - ). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/uri.gleam", 217). --spec query_to_string(list({binary(), binary()})) -> binary(). -query_to_string(Query) -> - _pipe = Query, - _pipe@1 = gleam@list:map(_pipe, fun query_pair/1), - _pipe@2 = gleam@list:intersperse( - _pipe@1, - gleam@string_builder:from_string(<<"&"/utf8>>) - ), - _pipe@3 = gleam@string_builder:concat(_pipe@2), - gleam@string_builder:to_string(_pipe@3). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/uri.gleam", 259). --spec percent_decode(binary()) -> {ok, binary()} | {error, nil}. -percent_decode(Value) -> - gleam_stdlib:percent_decode(Value). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/uri.gleam", 267). --spec do_remove_dot_segments(list(binary()), list(binary())) -> list(binary()). -do_remove_dot_segments(Input, Accumulator) -> - case Input of - [] -> - lists:reverse(Accumulator); - - [Segment | Rest] -> - Accumulator@5 = case {Segment, Accumulator} of - {<<""/utf8>>, Accumulator@1} -> - Accumulator@1; - - {<<"."/utf8>>, Accumulator@2} -> - Accumulator@2; - - {<<".."/utf8>>, []} -> - []; - - {<<".."/utf8>>, [_ | Accumulator@3]} -> - Accumulator@3; - - {Segment@1, Accumulator@4} -> - [Segment@1 | Accumulator@4] - end, - do_remove_dot_segments(Rest, Accumulator@5) - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/uri.gleam", 286). --spec remove_dot_segments(list(binary())) -> list(binary()). -remove_dot_segments(Input) -> - do_remove_dot_segments(Input, []). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/uri.gleam", 302). --spec path_segments(binary()) -> list(binary()). -path_segments(Path) -> - remove_dot_segments(gleam@string:split(Path, <<"/"/utf8>>)). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/uri.gleam", 318). --spec to_string(uri()) -> binary(). -to_string(Uri) -> - Parts = case erlang:element(8, Uri) of - {some, Fragment} -> - [<<"#"/utf8>>, Fragment]; - - _ -> - [] - end, - Parts@1 = case erlang:element(7, Uri) of - {some, Query} -> - [<<"?"/utf8>>, Query | Parts]; - - _ -> - Parts - end, - Parts@2 = [erlang:element(6, Uri) | Parts@1], - Parts@3 = case {erlang:element(4, Uri), - gleam@string:starts_with(erlang:element(6, Uri), <<"/"/utf8>>)} of - {{some, Host}, false} when Host =/= <<""/utf8>> -> - [<<"/"/utf8>> | Parts@2]; - - {_, _} -> - Parts@2 - end, - Parts@4 = case {erlang:element(4, Uri), erlang:element(5, Uri)} of - {{some, _}, {some, Port}} -> - [<<":"/utf8>>, gleam@int:to_string(Port) | Parts@3]; - - {_, _} -> - Parts@3 - end, - Parts@5 = case {erlang:element(2, Uri), - erlang:element(3, Uri), - erlang:element(4, Uri)} of - {{some, S}, {some, U}, {some, H}} -> - [S, <<"://"/utf8>>, U, <<"@"/utf8>>, H | Parts@4]; - - {{some, S@1}, none, {some, H@1}} -> - [S@1, <<"://"/utf8>>, H@1 | Parts@4]; - - {{some, S@2}, {some, _}, none} -> - [S@2, <<":"/utf8>> | Parts@4]; - - {{some, S@2}, none, none} -> - [S@2, <<":"/utf8>> | Parts@4]; - - {none, none, {some, H@2}} -> - [<<"//"/utf8>>, H@2 | Parts@4]; - - {_, _, _} -> - Parts@4 - end, - gleam@string:concat(Parts@5). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/uri.gleam", 362). --spec origin(uri()) -> {ok, binary()} | {error, nil}. -origin(Uri) -> - {uri, Scheme, _, Host, Port, _, _, _} = Uri, - case {Host, Scheme} of - {{some, H}, {some, <<"https"/utf8>>}} when Port =:= {some, 443} -> - {ok, gleam@string:concat([<<"https://"/utf8>>, H])}; - - {{some, H@1}, {some, <<"http"/utf8>>}} when Port =:= {some, 80} -> - {ok, gleam@string:concat([<<"http://"/utf8>>, H@1])}; - - {{some, H@2}, {some, S}} when (S =:= <<"http"/utf8>>) orelse (S =:= <<"https"/utf8>>) -> - case Port of - {some, P} -> - {ok, - gleam@string:concat( - [S, - <<"://"/utf8>>, - H@2, - <<":"/utf8>>, - gleam@int:to_string(P)] - )}; - - none -> - {ok, gleam@string:concat([S, <<"://"/utf8>>, H@2])} - end; - - {_, _} -> - {error, nil} - end. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/uri.gleam", 379). --spec drop_last(list(FKL)) -> list(FKL). -drop_last(Elements) -> - gleam@list:take(Elements, erlang:length(Elements) - 1). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/uri.gleam", 383). --spec join_segments(list(binary())) -> binary(). -join_segments(Segments) -> - gleam@string:join([<<""/utf8>> | Segments], <<"/"/utf8>>). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/uri.gleam", 393). --spec merge(uri(), uri()) -> {ok, uri()} | {error, nil}. -merge(Base, Relative) -> - case Base of - {uri, {some, _}, _, {some, _}, _, _, _, _} -> - case Relative of - {uri, _, _, {some, _}, _, _, _, _} -> - Path = begin - _pipe = gleam@string:split( - erlang:element(6, Relative), - <<"/"/utf8>> - ), - _pipe@1 = remove_dot_segments(_pipe), - join_segments(_pipe@1) - end, - Resolved = {uri, - gleam@option:'or'( - erlang:element(2, Relative), - erlang:element(2, Base) - ), - none, - erlang:element(4, Relative), - gleam@option:'or'( - erlang:element(5, Relative), - erlang:element(5, Base) - ), - Path, - erlang:element(7, Relative), - erlang:element(8, Relative)}, - {ok, Resolved}; - - _ -> - {New_path, New_query} = case erlang:element(6, Relative) of - <<""/utf8>> -> - {erlang:element(6, Base), - gleam@option:'or'( - erlang:element(7, Relative), - erlang:element(7, Base) - )}; - - _ -> - Path_segments = case gleam@string:starts_with( - erlang:element(6, Relative), - <<"/"/utf8>> - ) of - true -> - gleam@string:split( - erlang:element(6, Relative), - <<"/"/utf8>> - ); - - false -> - _pipe@2 = gleam@string:split( - erlang:element(6, Base), - <<"/"/utf8>> - ), - _pipe@3 = drop_last(_pipe@2), - lists:append( - _pipe@3, - gleam@string:split( - erlang:element(6, Relative), - <<"/"/utf8>> - ) - ) - end, - Path@1 = begin - _pipe@4 = Path_segments, - _pipe@5 = remove_dot_segments(_pipe@4), - join_segments(_pipe@5) - end, - {Path@1, erlang:element(7, Relative)} - end, - Resolved@1 = {uri, - erlang:element(2, Base), - none, - erlang:element(4, Base), - erlang:element(5, Base), - New_path, - New_query, - erlang:element(8, Relative)}, - {ok, Resolved@1} - end; - - _ -> - {error, nil} - end. diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam_stdlib.erl b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam_stdlib.erl deleted file mode 100644 index 562ef2372a2..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam_stdlib.erl +++ /dev/null @@ -1,565 +0,0 @@ --module(gleam_stdlib). - --export([ - map_get/2, iodata_append/2, identity/1, decode_int/1, decode_bool/1, - decode_float/1, decode_list/1, decode_option/2, decode_field/2, parse_int/1, - parse_float/1, less_than/2, string_pop_grapheme/1, string_starts_with/2, - wrap_list/1, string_ends_with/2, string_pad/4, decode_map/1, uri_parse/1, - bit_array_int_to_u32/1, bit_array_int_from_u32/1, decode_result/1, - bit_array_slice/3, decode_bit_array/1, compile_regex/2, regex_scan/2, - percent_encode/1, percent_decode/1, regex_check/2, regex_split/2, - base_decode64/1, parse_query/1, bit_array_concat/1, - bit_array_base64_encode/2, size_of_tuple/1, - decode_tuple/1, decode_tuple2/1, decode_tuple3/1, decode_tuple4/1, - decode_tuple5/1, decode_tuple6/1, tuple_get/2, classify_dynamic/1, print/1, - println/1, print_error/1, println_error/1, inspect/1, float_to_string/1, - int_from_base_string/2, utf_codepoint_list_to_string/1, contains_string/2, - crop_string/2, base16_decode/1, string_replace/3, regex_replace/3, slice/3, bit_array_to_int_and_size/1 -]). - -%% Taken from OTP's uri_string module --define(DEC2HEX(X), - if ((X) >= 0) andalso ((X) =< 9) -> (X) + $0; - ((X) >= 10) andalso ((X) =< 15) -> (X) + $A - 10 - end). - -%% Taken from OTP's uri_string module --define(HEX2DEC(X), - if ((X) >= $0) andalso ((X) =< $9) -> (X) - $0; - ((X) >= $A) andalso ((X) =< $F) -> (X) - $A + 10; - ((X) >= $a) andalso ((X) =< $f) -> (X) - $a + 10 - end). - --define(is_lowercase_char(X), (X > 96 andalso X < 123)). --define(is_underscore_char(X), (X == 95)). --define(is_digit_char(X), (X > 47 andalso X < 58)). - -uppercase(X) -> X - 32. - -map_get(Map, Key) -> - case maps:find(Key, Map) of - error -> {error, nil}; - OkFound -> OkFound - end. - -iodata_append(Iodata, String) -> [Iodata, String]. - -identity(X) -> X. - -decode_error_msg(Expected, Data) when is_binary(Expected) -> - decode_error(Expected, classify_dynamic(Data)). -decode_error(Expected, Got) when is_binary(Expected) andalso is_binary(Got) -> - {error, [{decode_error, Expected, Got, []}]}. - -classify_dynamic(nil) -> <<"Nil">>; -classify_dynamic(X) when is_boolean(X) -> <<"Bool">>; -classify_dynamic(X) when is_atom(X) -> <<"Atom">>; -classify_dynamic(X) when is_binary(X) -> <<"String">>; -classify_dynamic(X) when is_bitstring(X) -> <<"BitArray">>; -classify_dynamic(X) when is_integer(X) -> <<"Int">>; -classify_dynamic(X) when is_float(X) -> <<"Float">>; -classify_dynamic(X) when is_list(X) -> <<"List">>; -classify_dynamic(X) when is_map(X) -> <<"Dict">>; -classify_dynamic(X) when is_tuple(X) -> - iolist_to_binary(["Tuple of ", integer_to_list(tuple_size(X)), " elements"]); -classify_dynamic(X) when - is_function(X, 0) orelse is_function(X, 1) orelse is_function(X, 2) orelse - is_function(X, 3) orelse is_function(X, 4) orelse is_function(X, 5) orelse - is_function(X, 6) orelse is_function(X, 7) orelse is_function(X, 8) orelse - is_function(X, 9) orelse is_function(X, 10) orelse is_function(X, 11) orelse - is_function(X, 12) -> <<"Function">>; -classify_dynamic(_) -> <<"Some other type">>. - -decode_map(Data) when is_map(Data) -> {ok, Data}; -decode_map(Data) -> decode_error_msg(<<"Dict">>, Data). - -decode_bit_array(Data) when is_bitstring(Data) -> {ok, Data}; -decode_bit_array(Data) -> decode_error_msg(<<"BitArray">>, Data). - -decode_int(Data) when is_integer(Data) -> {ok, Data}; -decode_int(Data) -> decode_error_msg(<<"Int">>, Data). - -decode_float(Data) when is_float(Data) -> {ok, Data}; -decode_float(Data) -> decode_error_msg(<<"Float">>, Data). - -decode_bool(Data) when is_boolean(Data) -> {ok, Data}; -decode_bool(Data) -> decode_error_msg(<<"Bool">>, Data). - -decode_list(Data) when is_list(Data) -> {ok, Data}; -decode_list(Data) -> decode_error_msg(<<"List">>, Data). - -decode_field(Data, Key) when is_map(Data) -> - case Data of - #{Key := Value} -> {ok, {some, Value}}; - _ -> - {ok, none} - end; -decode_field(Data, _) -> - decode_error_msg(<<"Dict">>, Data). - -size_of_tuple(Data) -> tuple_size(Data). - -tuple_get(_tup, Index) when Index < 0 -> {error, nil}; -tuple_get(Data, Index) when Index >= tuple_size(Data) -> {error, nil}; -tuple_get(Data, Index) -> {ok, element(Index + 1, Data)}. - -decode_tuple(Data) when is_tuple(Data) -> {ok, Data}; -decode_tuple(Data) -> decode_error_msg(<<"Tuple">>, Data). - -decode_tuple2({_,_} = A) -> {ok, A}; -decode_tuple2([A,B]) -> {ok, {A,B}}; -decode_tuple2(Data) -> decode_error_msg(<<"Tuple of 2 elements">>, Data). - -decode_tuple3({_,_,_} = A) -> {ok, A}; -decode_tuple3([A,B,C]) -> {ok, {A,B,C}}; -decode_tuple3(Data) -> decode_error_msg(<<"Tuple of 3 elements">>, Data). - -decode_tuple4({_,_,_,_} = A) -> {ok, A}; -decode_tuple4([A,B,C,D]) -> {ok, {A,B,C,D}}; -decode_tuple4(Data) -> decode_error_msg(<<"Tuple of 4 elements">>, Data). - -decode_tuple5({_,_,_,_,_} = A) -> {ok, A}; -decode_tuple5([A,B,C,D,E]) -> {ok, {A,B,C,D,E}}; -decode_tuple5(Data) -> decode_error_msg(<<"Tuple of 5 elements">>, Data). - -decode_tuple6({_,_,_,_,_,_} = A) -> {ok, A}; -decode_tuple6([A,B,C,D,E,F]) -> {ok, {A,B,C,D,E,F}}; -decode_tuple6(Data) -> decode_error_msg(<<"Tuple of 6 elements">>, Data). - -decode_option(Term, F) -> - Decode = fun(Inner) -> - case F(Inner) of - {ok, Decoded} -> {ok, {some, Decoded}}; - Error -> Error - end - end, - case Term of - undefined -> {ok, none}; - error -> {ok, none}; - null -> {ok, none}; - none -> {ok, none}; - nil -> {ok, none}; - {some, Inner} -> Decode(Inner); - _ -> Decode(Term) - end. - -decode_result(Term) -> - case Term of - {ok, Inner} -> {ok, {ok, Inner}}; - ok -> {ok, {ok, nil}}; - {error, Inner} -> {ok, {error, Inner}}; - error -> {ok, {error, nil}}; - _ -> decode_error_msg(<<"Result">>, Term) - end. - -int_from_base_string(String, Base) -> - case catch binary_to_integer(String, Base) of - Int when is_integer(Int) -> {ok, Int}; - _ -> {error, nil} - end. - -parse_int(String) -> - case catch binary_to_integer(String) of - Int when is_integer(Int) -> {ok, Int}; - _ -> {error, nil} - end. - -parse_float(String) -> - case catch binary_to_float(String) of - Float when is_float(Float) -> {ok, Float}; - _ -> {error, nil} - end. - -less_than(Lhs, Rhs) -> - Lhs < Rhs. - -string_starts_with(_, <<>>) -> true; -string_starts_with(String, Prefix) when byte_size(Prefix) > byte_size(String) -> false; -string_starts_with(String, Prefix) -> - PrefixSize = byte_size(Prefix), - Prefix == binary_part(String, 0, PrefixSize). - -string_ends_with(_, <<>>) -> true; -string_ends_with(String, Suffix) when byte_size(Suffix) > byte_size(String) -> false; -string_ends_with(String, Suffix) -> - SuffixSize = byte_size(Suffix), - Suffix == binary_part(String, byte_size(String) - SuffixSize, SuffixSize). - -string_pad(String, Length, Dir, PadString) -> - Chars = string:pad(String, Length, Dir, binary_to_list(PadString)), - case unicode:characters_to_binary(Chars) of - Bin when is_binary(Bin) -> Bin; - Error -> erlang:error({gleam_error, {string_invalid_utf8, Error}}) - end. - -string_pop_grapheme(String) -> - case string:next_grapheme(String) of - [ Next | Rest ] when is_binary(Rest) -> - {ok, {unicode:characters_to_binary([Next]), Rest}}; - - [ Next | Rest ] -> - {ok, {unicode:characters_to_binary([Next]), unicode:characters_to_binary(Rest)}}; - - _ -> {error, nil} - end. - -bit_array_concat(BitArrays) -> - list_to_bitstring(BitArrays). - --if(?OTP_RELEASE >= 26). -bit_array_base64_encode(Bin, Padding) -> - base64:encode(Bin, #{padding => Padding}). --else. -bit_array_base64_encode(_Bin, _Padding) -> - erlang:error(<<"Erlang OTP/26 or higher is required to use base64:encode">>). --endif. - -bit_array_slice(Bin, Pos, Len) -> - try {ok, binary:part(Bin, Pos, Len)} - catch error:badarg -> {error, nil} - end. - -bit_array_int_to_u32(I) when 0 =< I, I < 4294967296 -> - {ok, <>}; -bit_array_int_to_u32(_) -> - {error, nil}. - -bit_array_int_from_u32(<>) -> - {ok, I}; -bit_array_int_from_u32(_) -> - {error, nil}. - -compile_regex(String, Options) -> - {options, Caseless, Multiline} = Options, - OptionsList = [ - unicode, - ucp, - Caseless andalso caseless, - Multiline andalso multiline - ], - FilteredOptions = [Option || Option <- OptionsList, Option /= false], - case re:compile(String, FilteredOptions) of - {ok, MP} -> {ok, MP}; - {error, {Str, Pos}} -> - {error, {compile_error, unicode:characters_to_binary(Str), Pos}} - end. - -regex_check(Regex, String) -> - re:run(String, Regex) /= nomatch. - -regex_split(Regex, String) -> - re:split(String, Regex). - -regex_submatches(_, {-1, 0}) -> none; -regex_submatches(String, {Start, Length}) -> - BinarySlice = binary:part(String, {Start, Length}), - case string:is_empty(binary_to_list(BinarySlice)) of - true -> none; - false -> {some, BinarySlice} - end. - -regex_matches(String, [{Start, Length} | Submatches]) -> - Submatches1 = lists:map(fun(X) -> regex_submatches(String, X) end, Submatches), - {match, binary:part(String, Start, Length), Submatches1}. - -regex_scan(Regex, String) -> - case re:run(String, Regex, [global]) of - {match, Captured} -> lists:map(fun(X) -> regex_matches(String, X) end, Captured); - nomatch -> [] - end. - -regex_replace(Regex, Subject, Replacement) -> - re:replace(Subject, Regex, Replacement, [global, {return, binary}]). - -base_decode64(S) -> - try {ok, base64:decode(S)} - catch error:_ -> {error, nil} - end. - -wrap_list(X) when is_list(X) -> X; -wrap_list(X) -> [X]. - -parse_query(Query) -> - case uri_string:dissect_query(Query) of - {error, _, _} -> {error, nil}; - Pairs -> - Pairs1 = lists:map(fun - ({K, true}) -> {K, <<"">>}; - (Pair) -> Pair - end, Pairs), - {ok, Pairs1} - end. - -percent_encode(B) -> percent_encode(B, <<>>). -percent_encode(<<>>, Acc) -> - Acc; -percent_encode(<>, Acc) -> - case percent_ok(H) of - true -> - percent_encode(T, <>); - false -> - <> = <>, - percent_encode(T, <>) - end. - -percent_decode(Cs) -> percent_decode(Cs, <<>>). -percent_decode(<<$%, C0, C1, Cs/binary>>, Acc) -> - case is_hex_digit(C0) andalso is_hex_digit(C1) of - true -> - B = ?HEX2DEC(C0)*16+?HEX2DEC(C1), - percent_decode(Cs, <>); - false -> - {error, nil} - end; -percent_decode(<>, Acc) -> - percent_decode(Cs, <>); -percent_decode(<<>>, Acc) -> - check_utf8(Acc). - -percent_ok($!) -> true; -percent_ok($$) -> true; -percent_ok($') -> true; -percent_ok($() -> true; -percent_ok($)) -> true; -percent_ok($*) -> true; -percent_ok($+) -> true; -percent_ok($-) -> true; -percent_ok($.) -> true; -percent_ok($_) -> true; -percent_ok($~) -> true; -percent_ok(C) when $0 =< C, C =< $9 -> true; -percent_ok(C) when $A =< C, C =< $Z -> true; -percent_ok(C) when $a =< C, C =< $z -> true; -percent_ok(_) -> false. - -is_hex_digit(C) -> - ($0 =< C andalso C =< $9) orelse ($a =< C andalso C =< $f) orelse ($A =< C andalso C =< $F). - -check_utf8(Cs) -> - case unicode:characters_to_list(Cs) of - {incomplete, _, _} -> {error, nil}; - {error, _, _} -> {error, nil}; - _ -> {ok, Cs} - end. - -uri_parse(String) -> - case uri_string:parse(String) of - {error, _, _} -> {error, nil}; - Uri -> - {ok, {uri, - maps_get_optional(Uri, scheme), - maps_get_optional(Uri, userinfo), - maps_get_optional(Uri, host), - maps_get_optional(Uri, port), - maps_get_or(Uri, path, <<>>), - maps_get_optional(Uri, query), - maps_get_optional(Uri, fragment) - }} - end. - -maps_get_optional(Map, Key) -> - try {some, maps:get(Key, Map)} - catch _:_ -> none - end. - -maps_get_or(Map, Key, Default) -> - try maps:get(Key, Map) - catch _:_ -> Default - end. - -print(String) -> - io:put_chars(String), - nil. - -println(String) -> - io:put_chars([String, $\n]), - nil. - -print_error(String) -> - io:put_chars(standard_error, String), - nil. - -println_error(String) -> - io:put_chars(standard_error, [String, $\n]), - nil. - -inspect(true) -> - "True"; -inspect(false) -> - "False"; -inspect(nil) -> - "Nil"; -inspect(Data) when is_map(Data) -> - Fields = [ - [<<"#(">>, inspect(Key), <<", ">>, inspect(Value), <<")">>] - || {Key, Value} <- maps:to_list(Data) - ], - ["dict.from_list([", lists:join(", ", Fields), "])"]; -inspect(Atom) when is_atom(Atom) -> - Binary = erlang:atom_to_binary(Atom), - case inspect_maybe_gleam_atom(Binary, none, <<>>) of - {ok, Inspected} -> Inspected; - {error, _} -> ["atom.create_from_string(\"", Binary, "\")"] - end; -inspect(Any) when is_integer(Any) -> - erlang:integer_to_list(Any); -inspect(Any) when is_float(Any) -> - io_lib_format:fwrite_g(Any); -inspect(Binary) when is_binary(Binary) -> - case inspect_maybe_utf8_string(Binary, <<>>) of - {ok, InspectedUtf8String} -> InspectedUtf8String; - {error, not_a_utf8_string} -> - Segments = [erlang:integer_to_list(X) || <> <= Binary], - ["<<", lists:join(", ", Segments), ">>"] - end; -inspect(Bits) when is_bitstring(Bits) -> - inspect_bit_array(Bits); -inspect(List) when is_list(List) -> - case inspect_list(List) of - {proper, Elements} -> ["[", Elements, "]"]; - {improper, Elements} -> ["//erl([", Elements, "])"] - end; -inspect(Any) when is_tuple(Any) % Record constructors - andalso is_atom(element(1, Any)) - andalso element(1, Any) =/= false - andalso element(1, Any) =/= true - andalso element(1, Any) =/= nil --> - [Atom | ArgsList] = erlang:tuple_to_list(Any), - Args = lists:join(<<", ">>, - lists:map(fun inspect/1, ArgsList) - ), - [inspect(Atom), "(", Args, ")"]; -inspect(Tuple) when is_tuple(Tuple) -> - Elements = lists:map(fun inspect/1, erlang:tuple_to_list(Tuple)), - ["#(", lists:join(", ", Elements), ")"]; -inspect(Any) when is_function(Any) -> - {arity, Arity} = erlang:fun_info(Any, arity), - ArgsAsciiCodes = lists:seq($a, $a + Arity - 1), - Args = lists:join(<<", ">>, - lists:map(fun(Arg) -> <> end, ArgsAsciiCodes) - ), - ["//fn(", Args, ") { ... }"]; -inspect(Any) -> - ["//erl(", io_lib:format("~p", [Any]), ")"]. - - -inspect_maybe_gleam_atom(<<>>, none, _) -> - {error, nil}; -inspect_maybe_gleam_atom(<>, none, _) when ?is_digit_char(First) -> - {error, nil}; -inspect_maybe_gleam_atom(<<"_", _Rest/binary>>, none, _) -> - {error, nil}; -inspect_maybe_gleam_atom(<<"_">>, _PrevChar, _Acc) -> - {error, nil}; -inspect_maybe_gleam_atom(<<"_", _Rest/binary>>, $_, _Acc) -> - {error, nil}; -inspect_maybe_gleam_atom(<>, _PrevChar, _Acc) - when not (?is_lowercase_char(First) orelse ?is_underscore_char(First) orelse ?is_digit_char(First)) -> - {error, nil}; -inspect_maybe_gleam_atom(<>, none, Acc) -> - inspect_maybe_gleam_atom(Rest, First, <>); -inspect_maybe_gleam_atom(<<"_", Rest/binary>>, _PrevChar, Acc) -> - inspect_maybe_gleam_atom(Rest, $_, Acc); -inspect_maybe_gleam_atom(<>, $_, Acc) -> - inspect_maybe_gleam_atom(Rest, First, <>); -inspect_maybe_gleam_atom(<>, _PrevChar, Acc) -> - inspect_maybe_gleam_atom(Rest, First, <>); -inspect_maybe_gleam_atom(<<>>, _PrevChar, Acc) -> - {ok, Acc}; -inspect_maybe_gleam_atom(A, B, C) -> - erlang:display({A, B, C}), - throw({gleam_error, A, B, C}). - -inspect_list([]) -> - {proper, []}; -inspect_list([First]) -> - {proper, [inspect(First)]}; -inspect_list([First | Rest]) when is_list(Rest) -> - {Kind, Inspected} = inspect_list(Rest), - {Kind, [inspect(First), <<", ">> | Inspected]}; -inspect_list([First | ImproperTail]) -> - {improper, [inspect(First), <<" | ">>, inspect(ImproperTail)]}. - -inspect_bit_array(Bits) -> - Text = inspect_bit_array(Bits, <<"<<">>), - <>">>. - -inspect_bit_array(<<>>, Acc) -> - Acc; -inspect_bit_array(<>, Acc) -> - inspect_bit_array(Rest, append_segment(Acc, erlang:integer_to_binary(X))); -inspect_bit_array(Rest, Acc) -> - Size = bit_size(Rest), - <> = Rest, - X1 = erlang:integer_to_binary(X), - Size1 = erlang:integer_to_binary(Size), - Segment = <>, - inspect_bit_array(<<>>, append_segment(Acc, Segment)). - -bit_array_to_int_and_size(A) -> - Size = bit_size(A), - <> = A, - {A1, Size}. - -append_segment(<<"<<">>, Segment) -> - <<"<<", Segment/binary>>; -append_segment(Acc, Segment) -> - <>. - - -inspect_maybe_utf8_string(Binary, Acc) -> - case Binary of - <<>> -> {ok, <<$", Acc/binary, $">>}; - <> -> - Escaped = case First of - $" -> <<$\\, $">>; - $\\ -> <<$\\, $\\>>; - $\r -> <<$\\, $r>>; - $\n -> <<$\\, $n>>; - $\t -> <<$\\, $t>>; - $\f -> <<$\\, $f>>; - X when X > 126, X < 160 -> convert_to_u(X); - X when X < 32 -> convert_to_u(X); - Other -> <> - end, - inspect_maybe_utf8_string(Rest, <>); - _ -> {error, not_a_utf8_string} - end. - -convert_to_u(Code) -> - list_to_binary(io_lib:format("\\u{~4.16.0B}", [Code])). - -float_to_string(Float) when is_float(Float) -> - erlang:iolist_to_binary(io_lib_format:fwrite_g(Float)). - -utf_codepoint_list_to_string(List) -> - case unicode:characters_to_binary(List) of - {error, _} -> erlang:error({gleam_error, {string_invalid_utf8, List}}); - Binary -> Binary - end. - -crop_string(String, Prefix) -> - case string:find(String, Prefix) of - nomatch -> String; - New -> New - end. - -contains_string(String, Substring) -> - is_bitstring(string:find(String, Substring)). - -base16_decode(String) -> - try - {ok, binary:decode_hex(String)} - catch - _:_ -> {error, nil} - end. - -string_replace(String, Pattern, Replacement) -> - string:replace(String, Pattern, Replacement, all). - -slice(String, Index, Length) -> - case string:slice(String, Index, Length) of - X when is_binary(X) -> X; - X when is_list(X) -> unicode:characters_to_binary(X) - end. diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam_stdlib.mjs b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam_stdlib.mjs deleted file mode 100644 index 74df3d05952..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/_gleam_artefacts/gleam_stdlib.mjs +++ /dev/null @@ -1,992 +0,0 @@ -import { - BitArray, - Error, - List, - Ok, - Result, - UtfCodepoint, - stringBits, - toBitArray, - NonEmpty, - CustomType, -} from "./gleam.mjs"; -import { - CompileError as RegexCompileError, - Match as RegexMatch, -} from "./gleam/regex.mjs"; -import { DecodeError } from "./gleam/dynamic.mjs"; -import { Some, None } from "./gleam/option.mjs"; -import { Eq, Gt, Lt } from "./gleam/order.mjs"; -import Dict from "./dict.mjs"; - -const Nil = undefined; -const NOT_FOUND = {}; - -export function identity(x) { - return x; -} - -export function parse_int(value) { - if (/^[-+]?(\d+)$/.test(value)) { - return new Ok(parseInt(value)); - } else { - return new Error(Nil); - } -} - -export function parse_float(value) { - if (/^[-+]?(\d+)\.(\d+)([eE][-+]?\d+)?$/.test(value)) { - return new Ok(parseFloat(value)); - } else { - return new Error(Nil); - } -} - -export function to_string(term) { - return term.toString(); -} - -export function float_to_string(float) { - const string = float.toString().replace('+', ''); - if (string.indexOf(".") >= 0) { - return string; - } else { - const index = string.indexOf("e"); - if (index >= 0) { - return string.slice(0, index) + '.0' + string.slice(index); - } else { - return string + ".0"; - } - } -} - -export function int_to_base_string(int, base) { - return int.toString(base).toUpperCase(); -} - -const int_base_patterns = { - 2: /[^0-1]/, - 3: /[^0-2]/, - 4: /[^0-3]/, - 5: /[^0-4]/, - 6: /[^0-5]/, - 7: /[^0-6]/, - 8: /[^0-7]/, - 9: /[^0-8]/, - 10: /[^0-9]/, - 11: /[^0-9a]/, - 12: /[^0-9a-b]/, - 13: /[^0-9a-c]/, - 14: /[^0-9a-d]/, - 15: /[^0-9a-e]/, - 16: /[^0-9a-f]/, - 17: /[^0-9a-g]/, - 18: /[^0-9a-h]/, - 19: /[^0-9a-i]/, - 20: /[^0-9a-j]/, - 21: /[^0-9a-k]/, - 22: /[^0-9a-l]/, - 23: /[^0-9a-m]/, - 24: /[^0-9a-n]/, - 25: /[^0-9a-o]/, - 26: /[^0-9a-p]/, - 27: /[^0-9a-q]/, - 28: /[^0-9a-r]/, - 29: /[^0-9a-s]/, - 30: /[^0-9a-t]/, - 31: /[^0-9a-u]/, - 32: /[^0-9a-v]/, - 33: /[^0-9a-w]/, - 34: /[^0-9a-x]/, - 35: /[^0-9a-y]/, - 36: /[^0-9a-z]/, -}; - -export function int_from_base_string(string, base) { - if (int_base_patterns[base].test(string.replace(/^-/, "").toLowerCase())) { - return new Error(Nil); - } - - const result = parseInt(string, base); - - if (isNaN(result)) { - return new Error(Nil); - } - - return new Ok(result); -} - -export function string_replace(string, target, substitute) { - if (typeof string.replaceAll !== "undefined") { - return string.replaceAll(target, substitute); - } - // Fallback for older Node.js versions: - // 1. - // 2. - // TODO: This fallback could be remove once Node.js 14 is EOL - // aka on or after 2024-04-30 - return string.replace( - // $& means the whole matched string - new RegExp(target.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g"), - substitute, - ); -} - -export function string_reverse(string) { - return [...string].reverse().join(""); -} - -export function string_length(string) { - if (string === "") { - return 0; - } - const iterator = graphemes_iterator(string); - if (iterator) { - let i = 0; - for (const _ of iterator) { - i++; - } - return i; - } else { - return string.match(/./gsu).length; - } -} - -export function graphemes(string) { - const iterator = graphemes_iterator(string); - if (iterator) { - return List.fromArray(Array.from(iterator).map((item) => item.segment)); - } else { - return List.fromArray(string.match(/./gsu)); - } -} - -let segmenter = undefined; - -function graphemes_iterator(string) { - if (globalThis.Intl && Intl.Segmenter) { - segmenter ||= new Intl.Segmenter(); - return segmenter.segment(string)[Symbol.iterator](); - } -} - -export function pop_grapheme(string) { - let first; - const iterator = graphemes_iterator(string); - if (iterator) { - first = iterator.next().value?.segment; - } else { - first = string.match(/./su)?.[0]; - } - if (first) { - return new Ok([first, string.slice(first.length)]); - } else { - return new Error(Nil); - } -} - -export function lowercase(string) { - return string.toLowerCase(); -} - -export function uppercase(string) { - return string.toUpperCase(); -} - -export function less_than(a, b) { - return a < b; -} - -export function add(a, b) { - return a + b; -} - -export function split(xs, pattern) { - return List.fromArray(xs.split(pattern)); -} - -export function join(xs, separator) { - const iterator = xs[Symbol.iterator](); - let result = iterator.next().value || ""; - let current = iterator.next(); - while (!current.done) { - result = result + separator + current.value; - current = iterator.next(); - } - return result; -} - -export function concat(xs) { - let result = ""; - for (const x of xs) { - result = result + x; - } - return result; -} - -export function length(data) { - return data.length; -} - -export function string_slice(string, idx, len) { - if (len <= 0 || idx >= string.length) { - return ""; - } - - const iterator = graphemes_iterator(string); - if (iterator) { - while (idx-- > 0) { - iterator.next(); - } - - let result = ""; - - while (len-- > 0) { - const v = iterator.next().value; - if (v === undefined) { - break; - } - - result += v.segment; - } - - return result; - } else { - return string.match(/./gsu).slice(idx, idx + len).join(""); - } -} - -export function crop_string(string, substring) { - return string.substring(string.indexOf(substring)); -} - -export function contains_string(haystack, needle) { - return haystack.indexOf(needle) >= 0; -} - -export function starts_with(haystack, needle) { - return haystack.startsWith(needle); -} - -export function ends_with(haystack, needle) { - return haystack.endsWith(needle); -} - -export function split_once(haystack, needle) { - const index = haystack.indexOf(needle); - if (index >= 0) { - const before = haystack.slice(0, index); - const after = haystack.slice(index + needle.length); - return new Ok([before, after]); - } else { - return new Error(Nil); - } -} - -const unicode_whitespaces = [ - "\u0020", // Space - "\u0009", // Horizontal tab - "\u000A", // Line feed - "\u000B", // Vertical tab - "\u000C", // Form feed - "\u000D", // Carriage return - "\u0085", // Next line - "\u2028", // Line separator - "\u2029", // Paragraph separator -].join(""); - -const left_trim_regex = new RegExp(`^([${unicode_whitespaces}]*)`, "g"); -const right_trim_regex = new RegExp(`([${unicode_whitespaces}]*)$`, "g"); - -export function trim(string) { - return trim_left(trim_right(string)); -} - -export function trim_left(string) { - return string.replace(left_trim_regex, ""); -} - -export function trim_right(string) { - return string.replace(right_trim_regex, ""); -} - -export function bit_array_from_string(string) { - return toBitArray([stringBits(string)]); -} - -export function bit_array_concat(bit_arrays) { - return toBitArray(bit_arrays.toArray().map((b) => b.buffer)); -} - -export function console_log(term) { - console.log(term); -} - -export function console_error(term) { - console.error(term); -} - -export function crash(message) { - throw new globalThis.Error(message); -} - -export function bit_array_to_string(bit_array) { - try { - const decoder = new TextDecoder("utf-8", { fatal: true }); - return new Ok(decoder.decode(bit_array.buffer)); - } catch { - return new Error(Nil); - } -} - -export function print(string) { - if (typeof process === "object") { - process.stdout.write(string); // We can write without a trailing newline - } else if (typeof Deno === "object") { - Deno.stdout.writeSync(new TextEncoder().encode(string)); // We can write without a trailing newline - } else { - console.log(string); // We're in a browser. Newlines are mandated - } -} - -export function print_error(string) { - if (typeof process === "object" && process.stderr?.write) { - process.stderr.write(string); // We can write without a trailing newline - } else if (typeof Deno === "object") { - Deno.stderr.writeSync(new TextEncoder().encode(string)); // We can write without a trailing newline - } else { - console.error(string); // We're in a browser. Newlines are mandated - } -} - -export function print_debug(string) { - if (typeof process === "object" && process.stderr?.write) { - process.stderr.write(string + "\n"); // If we're in Node.js, use `stderr` - } else if (typeof Deno === "object") { - Deno.stderr.writeSync(new TextEncoder().encode(string + "\n")); // If we're in Deno, use `stderr` - } else { - console.log(string); // Otherwise, use `console.log` (so that it doesn't look like an error) - } -} - -export function ceiling(float) { - return Math.ceil(float); -} - -export function floor(float) { - return Math.floor(float); -} - -export function round(float) { - return Math.round(float); -} - -export function truncate(float) { - return Math.trunc(float); -} - -export function power(base, exponent) { - // It is checked in Gleam that: - // - The base is non-negative and that the exponent is not fractional. - // - The base is non-zero and the exponent is non-negative (otherwise - // the result will essentially be division by zero). - // It can thus be assumed that valid input is passed to the Math.pow - // function and a NaN or Infinity value will not be produced. - return Math.pow(base, exponent); -} - -export function random_uniform() { - const random_uniform_result = Math.random(); - // With round-to-nearest-even behavior, the ranges claimed for the functions below - // (excluding the one for Math.random() itself) aren't exact. - // If extremely large bounds are chosen (2^53 or higher), - // it's possible in extremely rare cases to calculate the usually-excluded upper bound. - // Note that as numbers in JavaScript are IEEE 754 floating point numbers - // See: - // Because of this, we just loop 'until' we get a valid result where 0.0 <= x < 1.0: - if (random_uniform_result === 1.0) { - return random_uniform(); - } - return random_uniform_result; -} - -export function bit_array_slice(bits, position, length) { - const start = Math.min(position, position + length); - const end = Math.max(position, position + length); - if (start < 0 || end > bits.length) return new Error(Nil); - const byteOffset = bits.buffer.byteOffset + start; - const buffer = new Uint8Array( - bits.buffer.buffer, - byteOffset, - Math.abs(length), - ); - return new Ok(new BitArray(buffer)); -} - -export function codepoint(int) { - return new UtfCodepoint(int); -} - -export function string_to_codepoint_integer_list(string) { - return List.fromArray(Array.from(string).map((item) => item.codePointAt(0))); -} - -export function utf_codepoint_list_to_string(utf_codepoint_integer_list) { - return utf_codepoint_integer_list - .toArray() - .map((x) => String.fromCodePoint(x.value)) - .join(""); -} - -export function utf_codepoint_to_int(utf_codepoint) { - return utf_codepoint.value; -} - -export function regex_check(regex, string) { - regex.lastIndex = 0; - return regex.test(string); -} - -export function compile_regex(pattern, options) { - try { - let flags = "gu"; - if (options.case_insensitive) flags += "i"; - if (options.multi_line) flags += "m"; - return new Ok(new RegExp(pattern, flags)); - } catch (error) { - const number = (error.columnNumber || 0) | 0; - return new Error(new RegexCompileError(error.message, number)); - } -} - -export function regex_split(regex, string) { - return List.fromArray( - string.split(regex).map((item) => (item === undefined ? "" : item)), - ); -} - -export function regex_scan(regex, string) { - const matches = Array.from(string.matchAll(regex)).map((match) => { - const content = match[0]; - const submatches = []; - for (let n = match.length - 1; n > 0; n--) { - if (match[n]) { - submatches[n - 1] = new Some(match[n]); - continue; - } - if (submatches.length > 0) { - submatches[n - 1] = new None(); - } - } - return new RegexMatch(content, List.fromArray(submatches)); - }); - return List.fromArray(matches); -} - -export function regex_replace(regex, original_string, replacement) { - return original_string.replaceAll(regex, replacement); -} - -export function new_map() { - return Dict.new(); -} - -export function map_size(map) { - return map.size; -} - -export function map_to_list(map) { - return List.fromArray(map.entries()); -} - -export function map_remove(key, map) { - return map.delete(key); -} - -export function map_get(map, key) { - const value = map.get(key, NOT_FOUND); - if (value === NOT_FOUND) { - return new Error(Nil); - } - return new Ok(value); -} - -export function map_insert(key, value, map) { - return map.set(key, value); -} - -function unsafe_percent_decode(string) { - return decodeURIComponent(string || ""); -} - -function unsafe_percent_decode_query(string) { - return decodeURIComponent((string || "").replace("+", " ")); -} - -export function percent_decode(string) { - try { - return new Ok(unsafe_percent_decode(string)); - } catch { - return new Error(Nil); - } -} - -export function percent_encode(string) { - return encodeURIComponent(string).replace("%2B", "+"); -} - -export function parse_query(query) { - try { - const pairs = []; - for (const section of query.split("&")) { - const [key, value] = section.split("="); - if (!key) continue; - - const decodedKey = unsafe_percent_decode_query(key); - const decodedValue = unsafe_percent_decode_query(value); - pairs.push([decodedKey, decodedValue]); - } - return new Ok(List.fromArray(pairs)); - } catch { - return new Error(Nil); - } -} - -const b64EncodeLookup = [ - 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, - 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, - 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, - 122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43, 47, -]; - -let b64TextDecoder; - -// Implementation based on https://github.com/mitschabaude/fast-base64/blob/main/js.js -export function encode64(bit_array, padding) { - b64TextDecoder ??= new TextDecoder(); - - const bytes = bit_array.buffer; - - const m = bytes.length; - const k = m % 3; - const n = Math.floor(m / 3) * 4 + (k && k + 1); - const N = Math.ceil(m / 3) * 4; - const encoded = new Uint8Array(N); - - for (let i = 0, j = 0; j < m; i += 4, j += 3) { - const y = (bytes[j] << 16) + (bytes[j + 1] << 8) + (bytes[j + 2] | 0); - encoded[i] = b64EncodeLookup[y >> 18]; - encoded[i + 1] = b64EncodeLookup[(y >> 12) & 0x3f]; - encoded[i + 2] = b64EncodeLookup[(y >> 6) & 0x3f]; - encoded[i + 3] = b64EncodeLookup[y & 0x3f]; - } - - let base64 = b64TextDecoder.decode(new Uint8Array(encoded.buffer, 0, n)); - - if (padding) { - if (k === 1) { - base64 += "=="; - } else if (k === 2) { - base64 += "="; - } - } - - return base64; -} - -// From https://developer.mozilla.org/en-US/docs/Glossary/Base64 -export function decode64(sBase64) { - try { - const binString = atob(sBase64); - const length = binString.length; - const array = new Uint8Array(length); - for (let i = 0; i < length; i++) { - array[i] = binString.charCodeAt(i); - } - return new Ok(new BitArray(array)); - } catch { - return new Error(Nil); - } -} - -export function classify_dynamic(data) { - if (typeof data === "string") { - return "String"; - } else if (typeof data === "boolean") { - return "Bool"; - } else if (data instanceof Result) { - return "Result"; - } else if (data instanceof List) { - return "List"; - } else if (data instanceof BitArray) { - return "BitArray"; - } else if (data instanceof Dict) { - return "Dict"; - } else if (Number.isInteger(data)) { - return "Int"; - } else if (Array.isArray(data)) { - return `Tuple of ${data.length} elements`; - } else if (typeof data === "number") { - return "Float"; - } else if (data === null) { - return "Null"; - } else if (data === undefined) { - return "Nil"; - } else { - const type = typeof data; - return type.charAt(0).toUpperCase() + type.slice(1); - } -} - -function decoder_error(expected, got) { - return decoder_error_no_classify(expected, classify_dynamic(got)); -} - -function decoder_error_no_classify(expected, got) { - return new Error( - List.fromArray([new DecodeError(expected, got, List.fromArray([]))]), - ); -} - -export function decode_string(data) { - return typeof data === "string" - ? new Ok(data) - : decoder_error("String", data); -} - -export function decode_int(data) { - return Number.isInteger(data) ? new Ok(data) : decoder_error("Int", data); -} - -export function decode_float(data) { - return typeof data === "number" ? new Ok(data) : decoder_error("Float", data); -} - -export function decode_bool(data) { - return typeof data === "boolean" ? new Ok(data) : decoder_error("Bool", data); -} - -export function decode_bit_array(data) { - if (data instanceof BitArray) { - return new Ok(data); - } - if (data instanceof Uint8Array) { - return new Ok(new BitArray(data)); - } - return decoder_error("BitArray", data); -} - -export function decode_tuple(data) { - return Array.isArray(data) ? new Ok(data) : decoder_error("Tuple", data); -} - -export function decode_tuple2(data) { - return decode_tupleN(data, 2); -} - -export function decode_tuple3(data) { - return decode_tupleN(data, 3); -} - -export function decode_tuple4(data) { - return decode_tupleN(data, 4); -} - -export function decode_tuple5(data) { - return decode_tupleN(data, 5); -} - -export function decode_tuple6(data) { - return decode_tupleN(data, 6); -} - -function decode_tupleN(data, n) { - if (Array.isArray(data) && data.length == n) { - return new Ok(data); - } - - const list = decode_exact_length_list(data, n); - if (list) return new Ok(list); - - return decoder_error(`Tuple of ${n} elements`, data); -} - -function decode_exact_length_list(data, n) { - if (!(data instanceof List)) return; - - const elements = []; - let current = data; - - for (let i = 0; i < n; i++) { - if (!(current instanceof NonEmpty)) break; - elements.push(current.head); - current = current.tail; - } - - if (elements.length === n && !(current instanceof NonEmpty)) return elements; -} - -export function tuple_get(data, index) { - return index >= 0 && data.length > index - ? new Ok(data[index]) - : new Error(Nil); -} - -export function decode_list(data) { - if (Array.isArray(data)) { - return new Ok(List.fromArray(data)); - } - return data instanceof List ? new Ok(data) : decoder_error("List", data); -} - -export function decode_result(data) { - return data instanceof Result ? new Ok(data) : decoder_error("Result", data); -} - -export function decode_map(data) { - if (data instanceof Dict) { - return new Ok(data); - } - if (data instanceof Map || data instanceof WeakMap) { - return new Ok(Dict.fromMap(data)); - } - if (data == null) { - return decoder_error("Dict", data); - } - if (typeof data !== "object") { - return decoder_error("Dict", data); - } - const proto = Object.getPrototypeOf(data); - if (proto === Object.prototype || proto === null) { - return new Ok(Dict.fromObject(data)); - } - return decoder_error("Dict", data); -} - -export function decode_option(data, decoder) { - if (data === null || data === undefined || data instanceof None) - return new Ok(new None()); - if (data instanceof Some) data = data[0]; - const result = decoder(data); - if (result.isOk()) { - return new Ok(new Some(result[0])); - } else { - return result; - } -} - -export function decode_field(value, name) { - const not_a_map_error = () => decoder_error("Dict", value); - - if ( - value instanceof Dict || - value instanceof WeakMap || - value instanceof Map - ) { - const entry = map_get(value, name); - return new Ok(entry.isOk() ? new Some(entry[0]) : new None()); - } else if (value === null) { - return not_a_map_error(); - } else if (Object.getPrototypeOf(value) == Object.prototype) { - return try_get_field(value, name, () => new Ok(new None())); - } else { - return try_get_field(value, name, not_a_map_error); - } -} - -function try_get_field(value, field, or_else) { - try { - return field in value ? new Ok(new Some(value[field])) : or_else(); - } catch { - return or_else(); - } -} - -export function byte_size(string) { - return new TextEncoder().encode(string).length; -} - -// In Javascript bitwise operations convert numbers to a sequence of 32 bits -// while Erlang uses arbitrary precision. -// To get around this problem and get consistent results use BigInt and then -// downcast the value back to a Number value. - -export function bitwise_and(x, y) { - return Number(BigInt(x) & BigInt(y)); -} - -export function bitwise_not(x) { - return Number(~BigInt(x)); -} - -export function bitwise_or(x, y) { - return Number(BigInt(x) | BigInt(y)); -} - -export function bitwise_exclusive_or(x, y) { - return Number(BigInt(x) ^ BigInt(y)); -} - -export function bitwise_shift_left(x, y) { - return Number(BigInt(x) << BigInt(y)); -} - -export function bitwise_shift_right(x, y) { - return Number(BigInt(x) >> BigInt(y)); -} - -export function inspect(v) { - const t = typeof v; - if (v === true) return "True"; - if (v === false) return "False"; - if (v === null) return "//js(null)"; - if (v === undefined) return "Nil"; - if (t === "string") return inspectString(v); - if (t === "bigint" || Number.isInteger(v)) return v.toString(); - if (t === "number") return float_to_string(v); - if (Array.isArray(v)) return `#(${v.map(inspect).join(", ")})`; - if (v instanceof List) return inspectList(v); - if (v instanceof UtfCodepoint) return inspectUtfCodepoint(v); - if (v instanceof BitArray) return inspectBitArray(v); - if (v instanceof CustomType) return inspectCustomType(v); - if (v instanceof Dict) return inspectDict(v); - if (v instanceof Set) return `//js(Set(${[...v].map(inspect).join(", ")}))`; - if (v instanceof RegExp) return `//js(${v})`; - if (v instanceof Date) return `//js(Date("${v.toISOString()}"))`; - if (v instanceof Function) { - const args = []; - for (const i of Array(v.length).keys()) - args.push(String.fromCharCode(i + 97)); - return `//fn(${args.join(", ")}) { ... }`; - } - return inspectObject(v); -} - -function inspectString(str) { - let new_str = '"'; - for (let i = 0; i < str.length; i++) { - let char = str[i]; - switch (char) { - case "\n": - new_str += "\\n"; - break; - case "\r": - new_str += "\\r"; - break; - case "\t": - new_str += "\\t"; - break; - case "\f": - new_str += "\\f"; - break; - case "\\": - new_str += "\\\\"; - break; - case '"': - new_str += '\\"'; - break; - default: - if (char < " " || (char > "~" && char < "\u{00A0}")) { - new_str += - "\\u{" + - char.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0") + - "}"; - } else { - new_str += char; - } - } - } - new_str += '"'; - return new_str; -} - -function inspectDict(map) { - let body = "dict.from_list(["; - let first = true; - map.forEach((value, key) => { - if (!first) body = body + ", "; - body = body + "#(" + inspect(key) + ", " + inspect(value) + ")"; - first = false; - }); - return body + "])"; -} - -function inspectObject(v) { - const name = Object.getPrototypeOf(v)?.constructor?.name || "Object"; - const props = []; - for (const k of Object.keys(v)) { - props.push(`${inspect(k)}: ${inspect(v[k])}`); - } - const body = props.length ? " " + props.join(", ") + " " : ""; - const head = name === "Object" ? "" : name + " "; - return `//js(${head}{${body}})`; -} - -function inspectCustomType(record) { - const props = Object.keys(record) - .map((label) => { - const value = inspect(record[label]); - return isNaN(parseInt(label)) ? `${label}: ${value}` : value; - }) - .join(", "); - return props - ? `${record.constructor.name}(${props})` - : record.constructor.name; -} - -export function inspectList(list) { - return `[${list.toArray().map(inspect).join(", ")}]`; -} - -export function inspectBitArray(bits) { - return `<<${Array.from(bits.buffer).join(", ")}>>`; -} - -export function inspectUtfCodepoint(codepoint) { - return `//utfcodepoint(${String.fromCodePoint(codepoint.value)})`; -} - -export function base16_encode(bit_array) { - let result = ""; - for (const byte of bit_array.buffer) { - result += byte.toString(16).padStart(2, "0").toUpperCase(); - } - return result; -} - -export function base16_decode(string) { - const bytes = new Uint8Array(string.length / 2); - for (let i = 0; i < string.length; i += 2) { - const a = parseInt(string[i], 16); - const b = parseInt(string[i + 1], 16); - if (isNaN(a) || isNaN(b)) return new Error(Nil); - bytes[i / 2] = a * 16 + b; - } - return new Ok(new BitArray(bytes)); -} - -export function bit_array_inspect(bits, acc) { - return `${acc}${[...bits.buffer].join(", ")}`; -} - -export function bit_array_compare(first, second) { - for (let i = 0; i < first.length; i++) { - if (i >= second.length) { - return new Gt(); // first has more items - } - const f = first.buffer[i]; - const s = second.buffer[i]; - if (f > s) { - return new Gt(); - } - if (f < s) { - return new Lt(); - } - } - // This means that either first did not have any items - // or all items in first were equal to second. - if (first.length === second.length) { - return new Eq(); - } - return new Lt(); // second has more items -} diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/ebin/gleam_stdlib.app b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/ebin/gleam_stdlib.app deleted file mode 100644 index 88c7f140d57..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/ebin/gleam_stdlib.app +++ /dev/null @@ -1,27 +0,0 @@ -{application, gleam_stdlib, [ - {vsn, "0.41.0"}, - {applications, []}, - {description, "A standard library for the Gleam programming language"}, - {modules, [gleam@bit_array, - gleam@bool, - gleam@bytes_builder, - gleam@dict, - gleam@dynamic, - gleam@float, - gleam@function, - gleam@int, - gleam@io, - gleam@iterator, - gleam@list, - gleam@option, - gleam@order, - gleam@pair, - gleam@queue, - gleam@regex, - gleam@result, - gleam@set, - gleam@string, - gleam@string_builder, - gleam@uri]}, - {registered, []} -]}. diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/include/gleam@dynamic_DecodeError.hrl b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/include/gleam@dynamic_DecodeError.hrl deleted file mode 100644 index b1135f2dea0..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/include/gleam@dynamic_DecodeError.hrl +++ /dev/null @@ -1,5 +0,0 @@ --record(decode_error, { - expected :: binary(), - found :: binary(), - path :: list(binary()) -}). diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/include/gleam@iterator_Iterator.hrl b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/include/gleam@iterator_Iterator.hrl deleted file mode 100644 index b0d08dc71a3..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/include/gleam@iterator_Iterator.hrl +++ /dev/null @@ -1 +0,0 @@ --record(iterator, {continuation :: fun(() -> gleam@iterator:action(any()))}). diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/include/gleam@iterator_Next.hrl b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/include/gleam@iterator_Next.hrl deleted file mode 100644 index 1f61922beda..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/include/gleam@iterator_Next.hrl +++ /dev/null @@ -1 +0,0 @@ --record(next, {element :: any(), accumulator :: any()}). diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/include/gleam@queue_Queue.hrl b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/include/gleam@queue_Queue.hrl deleted file mode 100644 index 88ac25ed0a7..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/include/gleam@queue_Queue.hrl +++ /dev/null @@ -1 +0,0 @@ --record(queue, {in :: list(any()), out :: list(any())}). diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/include/gleam@regex_CompileError.hrl b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/include/gleam@regex_CompileError.hrl deleted file mode 100644 index ad5511eb103..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/include/gleam@regex_CompileError.hrl +++ /dev/null @@ -1 +0,0 @@ --record(compile_error, {error :: binary(), byte_index :: integer()}). diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/include/gleam@regex_Match.hrl b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/include/gleam@regex_Match.hrl deleted file mode 100644 index 42166198699..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/include/gleam@regex_Match.hrl +++ /dev/null @@ -1,4 +0,0 @@ --record(match, { - content :: binary(), - submatches :: list(gleam@option:option(binary())) -}). diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/include/gleam@regex_Options.hrl b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/include/gleam@regex_Options.hrl deleted file mode 100644 index 0074603b961..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/include/gleam@regex_Options.hrl +++ /dev/null @@ -1 +0,0 @@ --record(options, {case_insensitive :: boolean(), multi_line :: boolean()}). diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/include/gleam@set_Set.hrl b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/include/gleam@set_Set.hrl deleted file mode 100644 index 51fb7787567..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/include/gleam@set_Set.hrl +++ /dev/null @@ -1 +0,0 @@ --record(set, {dict :: gleam@dict:dict(any(), list(nil))}). diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/include/gleam@uri_Uri.hrl b/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/include/gleam@uri_Uri.hrl deleted file mode 100644 index 50150f476b1..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/gleam_stdlib/include/gleam@uri_Uri.hrl +++ /dev/null @@ -1,9 +0,0 @@ --record(uri, { - scheme :: gleam@option:option(binary()), - userinfo :: gleam@option:option(binary()), - host :: gleam@option:option(binary()), - port :: gleam@option:option(integer()), - path :: binary(), - 'query' :: gleam@option:option(binary()), - fragment :: gleam@option:option(binary()) -}). diff --git a/test-output/cases/echo_dict/build/dev/erlang/gleam_version b/test-output/cases/echo_dict/build/dev/erlang/gleam_version deleted file mode 100644 index 3e1ad720b13..00000000000 --- a/test-output/cases/echo_dict/build/dev/erlang/gleam_version +++ /dev/null @@ -1 +0,0 @@ -1.5.0 \ No newline at end of file diff --git a/test-output/cases/echo_dict/build/dev/javascript/echo_tuple/_gleam_artefacts/main.cache b/test-output/cases/echo_dict/build/dev/javascript/echo_tuple/_gleam_artefacts/main.cache deleted file mode 100644 index 254b5fec5b4..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/echo_tuple/_gleam_artefacts/main.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/echo_tuple/_gleam_artefacts/main.cache_meta b/test-output/cases/echo_dict/build/dev/javascript/echo_tuple/_gleam_artefacts/main.cache_meta deleted file mode 100644 index 575cfd6de40..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/echo_tuple/_gleam_artefacts/main.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/echo_tuple/_gleam_artefacts/main.cache_warnings b/test-output/cases/echo_dict/build/dev/javascript/echo_tuple/_gleam_artefacts/main.cache_warnings deleted file mode 100644 index 1b1cb4d44c5..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/echo_tuple/_gleam_artefacts/main.cache_warnings and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/echo_tuple/gleam.main.mjs b/test-output/cases/echo_dict/build/dev/javascript/echo_tuple/gleam.main.mjs deleted file mode 100644 index e230911e646..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/echo_tuple/gleam.main.mjs +++ /dev/null @@ -1,2 +0,0 @@ -import { main } from "./main.mjs"; -main(); diff --git a/test-output/cases/echo_dict/build/dev/javascript/echo_tuple/gleam.mjs b/test-output/cases/echo_dict/build/dev/javascript/echo_tuple/gleam.mjs deleted file mode 100644 index 197cbbc35d4..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/echo_tuple/gleam.mjs +++ /dev/null @@ -1 +0,0 @@ -export * from "../prelude.mjs"; diff --git a/test-output/cases/echo_dict/build/dev/javascript/echo_tuple/main.mjs b/test-output/cases/echo_dict/build/dev/javascript/echo_tuple/main.mjs deleted file mode 100644 index 8073fd170e0..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/echo_tuple/main.mjs +++ /dev/null @@ -1,135 +0,0 @@ -import * as $stdlib$dict from "../gleam_stdlib/dict.mjs"; -import * as $dict from "../gleam_stdlib/gleam/dict.mjs"; -import { - toList, - BitArray as $BitArray, - List as $List, - UtfCodepoint as $UtfCodepoint, - CustomType as $CustomType, -} from "./gleam.mjs"; - -export function main() { - echo($dict.new$(), "src/main.gleam", 4); - return echo( - $dict.from_list(toList([[1, "hello"], [2, "world!"]])), - "src/main.gleam", - 5, - ); -} - -function echo(value, file, line) { - const grey = "\u001b[90m"; - const reset_color = "\u001b[39m"; - const file_line = `${file}:${line}`; - const string_value = echo$inspect(value); - - if (typeof process === "object" && process.stderr?.write) { - // If we're in Node.js, use `stderr` - const string = `${grey}${file_line}${reset_color}\n${string_value}\n`; - process.stderr.write(string); - } else if (typeof Deno === "object") { - // If we're in Deno, use `stderr` - const string = `${grey}${file_line}${reset_color}\n${string_value}\n`; - Deno.stderr.writeSync(new TextEncoder().encode(string)); - } else { - // Otherwise, use `console.log` - // The browser's console.log doesn't support ansi escape codes - const string = `${file_line}\n${string_value}`; - console.log(string); - } - - return value; -} - -function echo$inspectString(str) { - let new_str = '"'; - for (let i = 0; i < str.length; i++) { - let char = str[i]; - if (char == "\n") new_str += "\\n"; - else if (char == "\r") new_str += "\\r"; - else if (char == "\t") new_str += "\\t"; - else if (char == "\f") new_str += "\\f"; - else if (char == "\\") new_str += "\\\\"; - else if (char == '"') new_str += '\\"'; - else if (char < " " || (char > "~" && char < "\u{00A0}")) { - new_str += "\\u{" + char.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0") + "}"; - } else { - new_str += char; - } - } - new_str += '"'; - return new_str; -} - -function echo$inspectDict(map) { - let body = "dict.from_list(["; - let first = true; - map.forEach((value, key) => { - if (!first) body = body + ", "; - body = body + "#(" + echo$inspect(key) + ", " + echo$inspect(value) + ")"; - first = false; - }); - return body + "])"; -} - -function echo$inspectCustomType(record) { - const props = Object.keys(record) - .map((label) => { - const value = echo$inspect(record[label]); - return isNaN(parseInt(label)) ? `${label}: ${value}` : value; - }) - .join(", "); - return props ? `${record.constructor.name}(${props})` : record.constructor.name; -} - -function echo$inspectObject(v) { - const name = Object.getPrototypeOf(v)?.constructor?.name || "Object"; - const props = []; - for (const k of Object.keys(v)) { - props.push(`${echo$inspect(k)}: ${echo$inspect(v[k])}`); - } - const body = props.length ? " " + props.join(", ") + " " : ""; - const head = name === "Object" ? "" : name + " "; - return `//js(${head}{${body}})`; -} - -function echo$inspect(v) { - const t = typeof v; - if (v === true) return "True"; - if (v === false) return "False"; - if (v === null) return "//js(null)"; - if (v === undefined) return "Nil"; - if (t === "string") return echo$inspectString(v); - if (t === "bigint" || t === "number") return v.toString(); - if (Array.isArray(v)) return `#(${v.map(echo$inspect).join(", ")})`; - if (v instanceof $List) return `[${v.toArray().map(echo$inspect).join(", ")}]`; - if (v instanceof $UtfCodepoint) return `//utfcodepoint(${String.fromCodePoint(v.value)})`; - if (v instanceof $BitArray) return `<<${Array.from(v.buffer).join(", ")}>>`; - if (v instanceof $CustomType) return echo$inspectCustomType(v); - if (echo$isDict(v)) return echo$inspectDict(v); - if (v instanceof Set) return `//js(Set(${[...v].map(echo$inspect).join(", ")}))`; - if (v instanceof RegExp) return `//js(${v})`; - if (v instanceof Date) return `//js(Date("${v.toISOString()}"))`; - if (v instanceof Function) { - const args = []; - for (const i of Array(v.length).keys()) args.push(String.fromCharCode(i + 97)); - return `//fn(${args.join(", ")}) { ... }`; - } - return echo$inspectObject(v); -} - -function echo$isDict(value) { - try { - // We can only check if an object is a stdlib Dict if it is one of the - // project's dependencies. - // The `Dict` class is the default export of `stdlib/dict.mjs` - // that we import as `$stdlib$dict`. - return value instanceof $stdlib$dict.default; - } catch { - // If stdlib is not one of the project's dependencies then `$stdlib$dict` - // will not have been imported and the check will throw an exception meaning - // we can't check if something is actually a `Dict`. - return false; - } -} - diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@bit_array.cache b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@bit_array.cache deleted file mode 100644 index 3f189be2871..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@bit_array.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@bit_array.cache_meta b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@bit_array.cache_meta deleted file mode 100644 index 7d2e0a9e3d4..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@bit_array.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@bool.cache b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@bool.cache deleted file mode 100644 index daae2086fce..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@bool.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@bool.cache_meta b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@bool.cache_meta deleted file mode 100644 index c0c214714a8..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@bool.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@bytes_builder.cache b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@bytes_builder.cache deleted file mode 100644 index 4f1ee945765..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@bytes_builder.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@bytes_builder.cache_meta b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@bytes_builder.cache_meta deleted file mode 100644 index 60ef071c41c..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@bytes_builder.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@dict.cache b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@dict.cache deleted file mode 100644 index 2534bde76aa..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@dict.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@dict.cache_meta b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@dict.cache_meta deleted file mode 100644 index 24d66986cea..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@dict.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@dynamic.cache b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@dynamic.cache deleted file mode 100644 index 5acf50ae8f1..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@dynamic.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@dynamic.cache_meta b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@dynamic.cache_meta deleted file mode 100644 index 7ff3f002393..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@dynamic.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@float.cache b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@float.cache deleted file mode 100644 index c94c51da392..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@float.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@float.cache_meta b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@float.cache_meta deleted file mode 100644 index 8e748265eb2..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@float.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@function.cache b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@function.cache deleted file mode 100644 index ea4d3722de7..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@function.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@function.cache_meta b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@function.cache_meta deleted file mode 100644 index 44e88039a8c..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@function.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@int.cache b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@int.cache deleted file mode 100644 index db38c4025a3..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@int.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@int.cache_meta b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@int.cache_meta deleted file mode 100644 index 84d31d8f4b7..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@int.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@io.cache b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@io.cache deleted file mode 100644 index 1cf8b3b4737..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@io.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@io.cache_meta b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@io.cache_meta deleted file mode 100644 index e584e3c1f3a..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@io.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@iterator.cache b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@iterator.cache deleted file mode 100644 index 96a27a526d6..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@iterator.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@iterator.cache_meta b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@iterator.cache_meta deleted file mode 100644 index 20a841e5b55..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@iterator.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@list.cache b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@list.cache deleted file mode 100644 index ad3337f5487..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@list.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@list.cache_meta b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@list.cache_meta deleted file mode 100644 index 9a43a6fe3fc..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@list.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@option.cache b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@option.cache deleted file mode 100644 index 392f3a28da7..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@option.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@option.cache_meta b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@option.cache_meta deleted file mode 100644 index 98dc30049f5..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@option.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@order.cache b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@order.cache deleted file mode 100644 index 926b9c99f08..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@order.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@order.cache_meta b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@order.cache_meta deleted file mode 100644 index 28e9c818294..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@order.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@pair.cache b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@pair.cache deleted file mode 100644 index 33ab86c4010..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@pair.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@pair.cache_meta b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@pair.cache_meta deleted file mode 100644 index 084e289d3e8..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@pair.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@queue.cache b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@queue.cache deleted file mode 100644 index 7731eb7edc8..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@queue.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@queue.cache_meta b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@queue.cache_meta deleted file mode 100644 index ef847119923..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@queue.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@regex.cache b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@regex.cache deleted file mode 100644 index 98f23356e4c..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@regex.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@regex.cache_meta b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@regex.cache_meta deleted file mode 100644 index 3dcdb710cd7..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@regex.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@result.cache b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@result.cache deleted file mode 100644 index b5c39949784..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@result.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@result.cache_meta b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@result.cache_meta deleted file mode 100644 index d8284f39a35..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@result.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@set.cache b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@set.cache deleted file mode 100644 index d85a25863ef..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@set.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@set.cache_meta b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@set.cache_meta deleted file mode 100644 index 14a143061a9..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@set.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@string.cache b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@string.cache deleted file mode 100644 index 5d8ce354882..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@string.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@string.cache_meta b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@string.cache_meta deleted file mode 100644 index 86962e061b7..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@string.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@string_builder.cache b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@string_builder.cache deleted file mode 100644 index 0dd0ac6d88f..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@string_builder.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@string_builder.cache_meta b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@string_builder.cache_meta deleted file mode 100644 index 72cc7bc898e..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@string_builder.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@uri.cache b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@uri.cache deleted file mode 100644 index 44c4c323b68..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@uri.cache and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@uri.cache_meta b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@uri.cache_meta deleted file mode 100644 index e5d8208db9a..00000000000 Binary files a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/_gleam_artefacts/gleam@uri.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/dict.mjs b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/dict.mjs deleted file mode 100644 index a8309e0cdbd..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/dict.mjs +++ /dev/null @@ -1,957 +0,0 @@ -/** - * This file uses jsdoc to annotate types. - * These types can be checked using the typescript compiler with "checkjs" option. - */ - -import { isEqual } from "./gleam.mjs"; - -const referenceMap = new WeakMap(); -const tempDataView = new DataView(new ArrayBuffer(8)); -let referenceUID = 0; -/** - * hash the object by reference using a weak map and incrementing uid - * @param {any} o - * @returns {number} - */ -function hashByReference(o) { - const known = referenceMap.get(o); - if (known !== undefined) { - return known; - } - const hash = referenceUID++; - if (referenceUID === 0x7fffffff) { - referenceUID = 0; - } - referenceMap.set(o, hash); - return hash; -} -/** - * merge two hashes in an order sensitive way - * @param {number} a - * @param {number} b - * @returns {number} - */ -function hashMerge(a, b) { - return (a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2))) | 0; -} -/** - * standard string hash popularised by java - * @param {string} s - * @returns {number} - */ -function hashString(s) { - let hash = 0; - const len = s.length; - for (let i = 0; i < len; i++) { - hash = (Math.imul(31, hash) + s.charCodeAt(i)) | 0; - } - return hash; -} -/** - * hash a number by converting to two integers and do some jumbling - * @param {number} n - * @returns {number} - */ -function hashNumber(n) { - tempDataView.setFloat64(0, n); - const i = tempDataView.getInt32(0); - const j = tempDataView.getInt32(4); - return Math.imul(0x45d9f3b, (i >> 16) ^ i) ^ j; -} -/** - * hash a BigInt by converting it to a string and hashing that - * @param {BigInt} n - * @returns {number} - */ -function hashBigInt(n) { - return hashString(n.toString()); -} -/** - * hash any js object - * @param {any} o - * @returns {number} - */ -function hashObject(o) { - const proto = Object.getPrototypeOf(o); - if (proto !== null && typeof proto.hashCode === "function") { - try { - const code = o.hashCode(o); - if (typeof code === "number") { - return code; - } - } catch {} - } - if (o instanceof Promise || o instanceof WeakSet || o instanceof WeakMap) { - return hashByReference(o); - } - if (o instanceof Date) { - return hashNumber(o.getTime()); - } - let h = 0; - if (o instanceof ArrayBuffer) { - o = new Uint8Array(o); - } - if (Array.isArray(o) || o instanceof Uint8Array) { - for (let i = 0; i < o.length; i++) { - h = (Math.imul(31, h) + getHash(o[i])) | 0; - } - } else if (o instanceof Set) { - o.forEach((v) => { - h = (h + getHash(v)) | 0; - }); - } else if (o instanceof Map) { - o.forEach((v, k) => { - h = (h + hashMerge(getHash(v), getHash(k))) | 0; - }); - } else { - const keys = Object.keys(o); - for (let i = 0; i < keys.length; i++) { - const k = keys[i]; - const v = o[k]; - h = (h + hashMerge(getHash(v), hashString(k))) | 0; - } - } - return h; -} -/** - * hash any js value - * @param {any} u - * @returns {number} - */ -export function getHash(u) { - if (u === null) return 0x42108422; - if (u === undefined) return 0x42108423; - if (u === true) return 0x42108421; - if (u === false) return 0x42108420; - switch (typeof u) { - case "number": - return hashNumber(u); - case "string": - return hashString(u); - case "bigint": - return hashBigInt(u); - case "object": - return hashObject(u); - case "symbol": - return hashByReference(u); - case "function": - return hashByReference(u); - default: - return 0; // should be unreachable - } -} -/** - * @template K,V - * @typedef {ArrayNode | IndexNode | CollisionNode} Node - */ -/** - * @template K,V - * @typedef {{ type: typeof ENTRY, k: K, v: V }} Entry - */ -/** - * @template K,V - * @typedef {{ type: typeof ARRAY_NODE, size: number, array: (undefined | Entry | Node)[] }} ArrayNode - */ -/** - * @template K,V - * @typedef {{ type: typeof INDEX_NODE, bitmap: number, array: (Entry | Node)[] }} IndexNode - */ -/** - * @template K,V - * @typedef {{ type: typeof COLLISION_NODE, hash: number, array: Entry[] }} CollisionNode - */ -/** - * @typedef {{ val: boolean }} Flag - */ -const SHIFT = 5; // number of bits you need to shift by to get the next bucket -const BUCKET_SIZE = Math.pow(2, SHIFT); -const MASK = BUCKET_SIZE - 1; // used to zero out all bits not in the bucket -const MAX_INDEX_NODE = BUCKET_SIZE / 2; // when does index node grow into array node -const MIN_ARRAY_NODE = BUCKET_SIZE / 4; // when does array node shrink to index node -const ENTRY = 0; -const ARRAY_NODE = 1; -const INDEX_NODE = 2; -const COLLISION_NODE = 3; -/** @type {IndexNode} */ -const EMPTY = { - type: INDEX_NODE, - bitmap: 0, - array: [], -}; -/** - * Mask the hash to get only the bucket corresponding to shift - * @param {number} hash - * @param {number} shift - * @returns {number} - */ -function mask(hash, shift) { - return (hash >>> shift) & MASK; -} -/** - * Set only the Nth bit where N is the masked hash - * @param {number} hash - * @param {number} shift - * @returns {number} - */ -function bitpos(hash, shift) { - return 1 << mask(hash, shift); -} -/** - * Count the number of 1 bits in a number - * @param {number} x - * @returns {number} - */ -function bitcount(x) { - x -= (x >> 1) & 0x55555555; - x = (x & 0x33333333) + ((x >> 2) & 0x33333333); - x = (x + (x >> 4)) & 0x0f0f0f0f; - x += x >> 8; - x += x >> 16; - return x & 0x7f; -} -/** - * Calculate the array index of an item in a bitmap index node - * @param {number} bitmap - * @param {number} bit - * @returns {number} - */ -function index(bitmap, bit) { - return bitcount(bitmap & (bit - 1)); -} -/** - * Efficiently copy an array and set one value at an index - * @template T - * @param {T[]} arr - * @param {number} at - * @param {T} val - * @returns {T[]} - */ -function cloneAndSet(arr, at, val) { - const len = arr.length; - const out = new Array(len); - for (let i = 0; i < len; ++i) { - out[i] = arr[i]; - } - out[at] = val; - return out; -} -/** - * Efficiently copy an array and insert one value at an index - * @template T - * @param {T[]} arr - * @param {number} at - * @param {T} val - * @returns {T[]} - */ -function spliceIn(arr, at, val) { - const len = arr.length; - const out = new Array(len + 1); - let i = 0; - let g = 0; - while (i < at) { - out[g++] = arr[i++]; - } - out[g++] = val; - while (i < len) { - out[g++] = arr[i++]; - } - return out; -} -/** - * Efficiently copy an array and remove one value at an index - * @template T - * @param {T[]} arr - * @param {number} at - * @returns {T[]} - */ -function spliceOut(arr, at) { - const len = arr.length; - const out = new Array(len - 1); - let i = 0; - let g = 0; - while (i < at) { - out[g++] = arr[i++]; - } - ++i; - while (i < len) { - out[g++] = arr[i++]; - } - return out; -} -/** - * Create a new node containing two entries - * @template K,V - * @param {number} shift - * @param {K} key1 - * @param {V} val1 - * @param {number} key2hash - * @param {K} key2 - * @param {V} val2 - * @returns {Node} - */ -function createNode(shift, key1, val1, key2hash, key2, val2) { - const key1hash = getHash(key1); - if (key1hash === key2hash) { - return { - type: COLLISION_NODE, - hash: key1hash, - array: [ - { type: ENTRY, k: key1, v: val1 }, - { type: ENTRY, k: key2, v: val2 }, - ], - }; - } - const addedLeaf = { val: false }; - return assoc( - assocIndex(EMPTY, shift, key1hash, key1, val1, addedLeaf), - shift, - key2hash, - key2, - val2, - addedLeaf - ); -} -/** - * @template T,K,V - * @callback AssocFunction - * @param {T} root - * @param {number} shift - * @param {number} hash - * @param {K} key - * @param {V} val - * @param {Flag} addedLeaf - * @returns {Node} - */ -/** - * Associate a node with a new entry, creating a new node - * @template T,K,V - * @type {AssocFunction,K,V>} - */ -function assoc(root, shift, hash, key, val, addedLeaf) { - switch (root.type) { - case ARRAY_NODE: - return assocArray(root, shift, hash, key, val, addedLeaf); - case INDEX_NODE: - return assocIndex(root, shift, hash, key, val, addedLeaf); - case COLLISION_NODE: - return assocCollision(root, shift, hash, key, val, addedLeaf); - } -} -/** - * @template T,K,V - * @type {AssocFunction,K,V>} - */ -function assocArray(root, shift, hash, key, val, addedLeaf) { - const idx = mask(hash, shift); - const node = root.array[idx]; - // if the corresponding index is empty set the index to a newly created node - if (node === undefined) { - addedLeaf.val = true; - return { - type: ARRAY_NODE, - size: root.size + 1, - array: cloneAndSet(root.array, idx, { type: ENTRY, k: key, v: val }), - }; - } - if (node.type === ENTRY) { - // if keys are equal replace the entry - if (isEqual(key, node.k)) { - if (val === node.v) { - return root; - } - return { - type: ARRAY_NODE, - size: root.size, - array: cloneAndSet(root.array, idx, { - type: ENTRY, - k: key, - v: val, - }), - }; - } - // otherwise upgrade the entry to a node and insert - addedLeaf.val = true; - return { - type: ARRAY_NODE, - size: root.size, - array: cloneAndSet( - root.array, - idx, - createNode(shift + SHIFT, node.k, node.v, hash, key, val) - ), - }; - } - // otherwise call assoc on the child node - const n = assoc(node, shift + SHIFT, hash, key, val, addedLeaf); - // if the child node hasn't changed just return the old root - if (n === node) { - return root; - } - // otherwise set the index to the new node - return { - type: ARRAY_NODE, - size: root.size, - array: cloneAndSet(root.array, idx, n), - }; -} -/** - * @template T,K,V - * @type {AssocFunction,K,V>} - */ -function assocIndex(root, shift, hash, key, val, addedLeaf) { - const bit = bitpos(hash, shift); - const idx = index(root.bitmap, bit); - // if there is already a item at this hash index.. - if ((root.bitmap & bit) !== 0) { - // if there is a node at the index (not an entry), call assoc on the child node - const node = root.array[idx]; - if (node.type !== ENTRY) { - const n = assoc(node, shift + SHIFT, hash, key, val, addedLeaf); - if (n === node) { - return root; - } - return { - type: INDEX_NODE, - bitmap: root.bitmap, - array: cloneAndSet(root.array, idx, n), - }; - } - // otherwise there is an entry at the index - // if the keys are equal replace the entry with the updated value - const nodeKey = node.k; - if (isEqual(key, nodeKey)) { - if (val === node.v) { - return root; - } - return { - type: INDEX_NODE, - bitmap: root.bitmap, - array: cloneAndSet(root.array, idx, { - type: ENTRY, - k: key, - v: val, - }), - }; - } - // if the keys are not equal, replace the entry with a new child node - addedLeaf.val = true; - return { - type: INDEX_NODE, - bitmap: root.bitmap, - array: cloneAndSet( - root.array, - idx, - createNode(shift + SHIFT, nodeKey, node.v, hash, key, val) - ), - }; - } else { - // else there is currently no item at the hash index - const n = root.array.length; - // if the number of nodes is at the maximum, expand this node into an array node - if (n >= MAX_INDEX_NODE) { - // create a 32 length array for the new array node (one for each bit in the hash) - const nodes = new Array(32); - // create and insert a node for the new entry - const jdx = mask(hash, shift); - nodes[jdx] = assocIndex(EMPTY, shift + SHIFT, hash, key, val, addedLeaf); - let j = 0; - let bitmap = root.bitmap; - // place each item in the index node into the correct spot in the array node - // loop through all 32 bits / array positions - for (let i = 0; i < 32; i++) { - if ((bitmap & 1) !== 0) { - const node = root.array[j++]; - nodes[i] = node; - } - // shift the bitmap to process the next bit - bitmap = bitmap >>> 1; - } - return { - type: ARRAY_NODE, - size: n + 1, - array: nodes, - }; - } else { - // else there is still space in this index node - // simply insert a new entry at the hash index - const newArray = spliceIn(root.array, idx, { - type: ENTRY, - k: key, - v: val, - }); - addedLeaf.val = true; - return { - type: INDEX_NODE, - bitmap: root.bitmap | bit, - array: newArray, - }; - } - } -} -/** - * @template T,K,V - * @type {AssocFunction,K,V>} - */ -function assocCollision(root, shift, hash, key, val, addedLeaf) { - // if there is a hash collision - if (hash === root.hash) { - const idx = collisionIndexOf(root, key); - // if this key already exists replace the entry with the new value - if (idx !== -1) { - const entry = root.array[idx]; - if (entry.v === val) { - return root; - } - return { - type: COLLISION_NODE, - hash: hash, - array: cloneAndSet(root.array, idx, { type: ENTRY, k: key, v: val }), - }; - } - // otherwise insert the entry at the end of the array - const size = root.array.length; - addedLeaf.val = true; - return { - type: COLLISION_NODE, - hash: hash, - array: cloneAndSet(root.array, size, { type: ENTRY, k: key, v: val }), - }; - } - // if there is no hash collision, upgrade to an index node - return assoc( - { - type: INDEX_NODE, - bitmap: bitpos(root.hash, shift), - array: [root], - }, - shift, - hash, - key, - val, - addedLeaf - ); -} -/** - * Find the index of a key in the collision node's array - * @template K,V - * @param {CollisionNode} root - * @param {K} key - * @returns {number} - */ -function collisionIndexOf(root, key) { - const size = root.array.length; - for (let i = 0; i < size; i++) { - if (isEqual(key, root.array[i].k)) { - return i; - } - } - return -1; -} -/** - * @template T,K,V - * @callback FindFunction - * @param {T} root - * @param {number} shift - * @param {number} hash - * @param {K} key - * @returns {undefined | Entry} - */ -/** - * Return the found entry or undefined if not present in the root - * @template K,V - * @type {FindFunction,K,V>} - */ -function find(root, shift, hash, key) { - switch (root.type) { - case ARRAY_NODE: - return findArray(root, shift, hash, key); - case INDEX_NODE: - return findIndex(root, shift, hash, key); - case COLLISION_NODE: - return findCollision(root, key); - } -} -/** - * @template K,V - * @type {FindFunction,K,V>} - */ -function findArray(root, shift, hash, key) { - const idx = mask(hash, shift); - const node = root.array[idx]; - if (node === undefined) { - return undefined; - } - if (node.type !== ENTRY) { - return find(node, shift + SHIFT, hash, key); - } - if (isEqual(key, node.k)) { - return node; - } - return undefined; -} -/** - * @template K,V - * @type {FindFunction,K,V>} - */ -function findIndex(root, shift, hash, key) { - const bit = bitpos(hash, shift); - if ((root.bitmap & bit) === 0) { - return undefined; - } - const idx = index(root.bitmap, bit); - const node = root.array[idx]; - if (node.type !== ENTRY) { - return find(node, shift + SHIFT, hash, key); - } - if (isEqual(key, node.k)) { - return node; - } - return undefined; -} -/** - * @template K,V - * @param {CollisionNode} root - * @param {K} key - * @returns {undefined | Entry} - */ -function findCollision(root, key) { - const idx = collisionIndexOf(root, key); - if (idx < 0) { - return undefined; - } - return root.array[idx]; -} -/** - * @template T,K,V - * @callback WithoutFunction - * @param {T} root - * @param {number} shift - * @param {number} hash - * @param {K} key - * @returns {undefined | Node} - */ -/** - * Remove an entry from the root, returning the updated root. - * Returns undefined if the node should be removed from the parent. - * @template K,V - * @type {WithoutFunction,K,V>} - * */ -function without(root, shift, hash, key) { - switch (root.type) { - case ARRAY_NODE: - return withoutArray(root, shift, hash, key); - case INDEX_NODE: - return withoutIndex(root, shift, hash, key); - case COLLISION_NODE: - return withoutCollision(root, key); - } -} -/** - * @template K,V - * @type {WithoutFunction,K,V>} - */ -function withoutArray(root, shift, hash, key) { - const idx = mask(hash, shift); - const node = root.array[idx]; - if (node === undefined) { - return root; // already empty - } - let n = undefined; - // if node is an entry and the keys are not equal there is nothing to remove - // if node is not an entry do a recursive call - if (node.type === ENTRY) { - if (!isEqual(node.k, key)) { - return root; // no changes - } - } else { - n = without(node, shift + SHIFT, hash, key); - if (n === node) { - return root; // no changes - } - } - // if the recursive call returned undefined the node should be removed - if (n === undefined) { - // if the number of child nodes is at the minimum, pack into an index node - if (root.size <= MIN_ARRAY_NODE) { - const arr = root.array; - const out = new Array(root.size - 1); - let i = 0; - let j = 0; - let bitmap = 0; - while (i < idx) { - const nv = arr[i]; - if (nv !== undefined) { - out[j] = nv; - bitmap |= 1 << i; - ++j; - } - ++i; - } - ++i; // skip copying the removed node - while (i < arr.length) { - const nv = arr[i]; - if (nv !== undefined) { - out[j] = nv; - bitmap |= 1 << i; - ++j; - } - ++i; - } - return { - type: INDEX_NODE, - bitmap: bitmap, - array: out, - }; - } - return { - type: ARRAY_NODE, - size: root.size - 1, - array: cloneAndSet(root.array, idx, n), - }; - } - return { - type: ARRAY_NODE, - size: root.size, - array: cloneAndSet(root.array, idx, n), - }; -} -/** - * @template K,V - * @type {WithoutFunction,K,V>} - */ -function withoutIndex(root, shift, hash, key) { - const bit = bitpos(hash, shift); - if ((root.bitmap & bit) === 0) { - return root; // already empty - } - const idx = index(root.bitmap, bit); - const node = root.array[idx]; - // if the item is not an entry - if (node.type !== ENTRY) { - const n = without(node, shift + SHIFT, hash, key); - if (n === node) { - return root; // no changes - } - // if not undefined, the child node still has items, so update it - if (n !== undefined) { - return { - type: INDEX_NODE, - bitmap: root.bitmap, - array: cloneAndSet(root.array, idx, n), - }; - } - // otherwise the child node should be removed - // if it was the only child node, remove this node from the parent - if (root.bitmap === bit) { - return undefined; - } - // otherwise just remove the child node - return { - type: INDEX_NODE, - bitmap: root.bitmap ^ bit, - array: spliceOut(root.array, idx), - }; - } - // otherwise the item is an entry, remove it if the key matches - if (isEqual(key, node.k)) { - if (root.bitmap === bit) { - return undefined; - } - return { - type: INDEX_NODE, - bitmap: root.bitmap ^ bit, - array: spliceOut(root.array, idx), - }; - } - return root; -} -/** - * @template K,V - * @param {CollisionNode} root - * @param {K} key - * @returns {undefined | Node} - */ -function withoutCollision(root, key) { - const idx = collisionIndexOf(root, key); - // if the key not found, no changes - if (idx < 0) { - return root; - } - // otherwise the entry was found, remove it - // if it was the only entry in this node, remove the whole node - if (root.array.length === 1) { - return undefined; - } - // otherwise just remove the entry - return { - type: COLLISION_NODE, - hash: root.hash, - array: spliceOut(root.array, idx), - }; -} -/** - * @template K,V - * @param {undefined | Node} root - * @param {(value:V,key:K)=>void} fn - * @returns {void} - */ -function forEach(root, fn) { - if (root === undefined) { - return; - } - const items = root.array; - const size = items.length; - for (let i = 0; i < size; i++) { - const item = items[i]; - if (item === undefined) { - continue; - } - if (item.type === ENTRY) { - fn(item.v, item.k); - continue; - } - forEach(item, fn); - } -} -/** - * Extra wrapper to keep track of Dict size and clean up the API - * @template K,V - */ -export default class Dict { - /** - * @template V - * @param {Record} o - * @returns {Dict} - */ - static fromObject(o) { - const keys = Object.keys(o); - /** @type Dict */ - let m = Dict.new(); - for (let i = 0; i < keys.length; i++) { - const k = keys[i]; - m = m.set(k, o[k]); - } - return m; - } - /** - * @template K,V - * @param {Map} o - * @returns {Dict} - */ - static fromMap(o) { - /** @type Dict */ - let m = Dict.new(); - o.forEach((v, k) => { - m = m.set(k, v); - }); - return m; - } - static new() { - return new Dict(undefined, 0); - } - /** - * @param {undefined | Node} root - * @param {number} size - */ - constructor(root, size) { - this.root = root; - this.size = size; - } - /** - * @template NotFound - * @param {K} key - * @param {NotFound} notFound - * @returns {NotFound | V} - */ - get(key, notFound) { - if (this.root === undefined) { - return notFound; - } - const found = find(this.root, 0, getHash(key), key); - if (found === undefined) { - return notFound; - } - return found.v; - } - /** - * @param {K} key - * @param {V} val - * @returns {Dict} - */ - set(key, val) { - const addedLeaf = { val: false }; - const root = this.root === undefined ? EMPTY : this.root; - const newRoot = assoc(root, 0, getHash(key), key, val, addedLeaf); - if (newRoot === this.root) { - return this; - } - return new Dict(newRoot, addedLeaf.val ? this.size + 1 : this.size); - } - /** - * @param {K} key - * @returns {Dict} - */ - delete(key) { - if (this.root === undefined) { - return this; - } - const newRoot = without(this.root, 0, getHash(key), key); - if (newRoot === this.root) { - return this; - } - if (newRoot === undefined) { - return Dict.new(); - } - return new Dict(newRoot, this.size - 1); - } - /** - * @param {K} key - * @returns {boolean} - */ - has(key) { - if (this.root === undefined) { - return false; - } - return find(this.root, 0, getHash(key), key) !== undefined; - } - /** - * @returns {[K,V][]} - */ - entries() { - if (this.root === undefined) { - return []; - } - /** @type [K,V][] */ - const result = []; - this.forEach((v, k) => result.push([k, v])); - return result; - } - /** - * - * @param {(val:V,key:K)=>void} fn - */ - forEach(fn) { - forEach(this.root, fn); - } - hashCode() { - let h = 0; - this.forEach((v, k) => { - h = (h + hashMerge(getHash(v), getHash(k))) | 0; - }); - return h; - } - /** - * @param {unknown} o - * @returns {boolean} - */ - equals(o) { - if (!(o instanceof Dict) || this.size !== o.size) { - return false; - } - let equal = true; - this.forEach((v, k) => { - equal = equal && isEqual(o.get(k, !v), v); - }); - return equal; - } -} diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam.mjs b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam.mjs deleted file mode 100644 index 197cbbc35d4..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam.mjs +++ /dev/null @@ -1 +0,0 @@ -export * from "../prelude.mjs"; diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/bit_array.mjs b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/bit_array.mjs deleted file mode 100644 index f092696e62f..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/bit_array.mjs +++ /dev/null @@ -1,79 +0,0 @@ -import { toList, remainderInt } from "../gleam.mjs"; -import * as $int from "../gleam/int.mjs"; -import * as $order from "../gleam/order.mjs"; -import * as $string from "../gleam/string.mjs"; -import { - bit_array_from_string as from_string, - length as byte_size, - bit_array_slice as slice, - bit_array_concat as concat, - encode64 as base64_encode, - decode64, - base16_encode, - base16_decode, - bit_array_inspect as do_inspect, - bit_array_compare as compare, - bit_array_to_string as do_to_string, -} from "../gleam_stdlib.mjs"; - -export { - base16_decode, - base16_encode, - base64_encode, - byte_size, - compare, - concat, - from_string, - slice, -}; - -export function append(first, second) { - return concat(toList([first, second])); -} - -export function base64_decode(encoded) { - let padded = (() => { - let $ = remainderInt(byte_size(from_string(encoded)), 4); - if ($ === 0) { - return encoded; - } else { - let n = $; - return $string.append(encoded, $string.repeat("=", 4 - n)); - } - })(); - return decode64(padded); -} - -export function base64_url_encode(input, padding) { - let _pipe = base64_encode(input, padding); - let _pipe$1 = $string.replace(_pipe, "+", "-"); - return $string.replace(_pipe$1, "/", "_"); -} - -export function base64_url_decode(encoded) { - let _pipe = encoded; - let _pipe$1 = $string.replace(_pipe, "-", "+"); - let _pipe$2 = $string.replace(_pipe$1, "_", "/"); - return base64_decode(_pipe$2); -} - -export function inspect(input) { - return do_inspect(input, "<<") + ">>"; -} - -export function is_utf8(bits) { - return do_is_utf8(bits); -} - -function do_is_utf8(bits) { - let $ = to_string(bits); - if ($.isOk()) { - return true; - } else { - return false; - } -} - -export function to_string(bits) { - return do_to_string(bits); -} diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/bool.mjs b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/bool.mjs deleted file mode 100644 index 3cc70057a03..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/bool.mjs +++ /dev/null @@ -1,73 +0,0 @@ -import * as $order from "../gleam/order.mjs"; - -export function and(a, b) { - return a && b; -} - -export function or(a, b) { - return a || b; -} - -export function negate(bool) { - return !bool; -} - -export function nor(a, b) { - return !(a || b); -} - -export function nand(a, b) { - return !(a && b); -} - -export function exclusive_or(a, b) { - return a !== b; -} - -export function exclusive_nor(a, b) { - return a === b; -} - -export function compare(a, b) { - if (a && b) { - return new $order.Eq(); - } else if (a && !b) { - return new $order.Gt(); - } else if (!a && !b) { - return new $order.Eq(); - } else { - return new $order.Lt(); - } -} - -export function to_int(bool) { - if (!bool) { - return 0; - } else { - return 1; - } -} - -export function to_string(bool) { - if (!bool) { - return "False"; - } else { - return "True"; - } -} - -export function guard(requirement, consequence, alternative) { - if (requirement) { - return consequence; - } else { - return alternative(); - } -} - -export function lazy_guard(requirement, consequence, alternative) { - if (requirement) { - return consequence(); - } else { - return alternative(); - } -} diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/bytes_builder.mjs b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/bytes_builder.mjs deleted file mode 100644 index ea37265d2db..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/bytes_builder.mjs +++ /dev/null @@ -1,134 +0,0 @@ -import { toList, prepend as listPrepend, CustomType as $CustomType } from "../gleam.mjs"; -import * as $bit_array from "../gleam/bit_array.mjs"; -import * as $list from "../gleam/list.mjs"; -import * as $string_builder from "../gleam/string_builder.mjs"; - -class Bytes extends $CustomType { - constructor(x0) { - super(); - this[0] = x0; - } -} - -class Text extends $CustomType { - constructor(x0) { - super(); - this[0] = x0; - } -} - -class Many extends $CustomType { - constructor(x0) { - super(); - this[0] = x0; - } -} - -export function append_builder(first, second) { - if (second instanceof Many) { - let builders = second[0]; - return new Many(listPrepend(first, builders)); - } else { - return new Many(toList([first, second])); - } -} - -export function prepend_builder(second, first) { - return append_builder(first, second); -} - -export function concat(builders) { - return new Many(builders); -} - -export function new$() { - return concat(toList([])); -} - -export function from_string(string) { - return new Text($string_builder.from_string(string)); -} - -export function prepend_string(second, first) { - return append_builder(from_string(first), second); -} - -export function append_string(first, second) { - return append_builder(first, from_string(second)); -} - -export function from_string_builder(builder) { - return new Text(builder); -} - -export function from_bit_array(bits) { - return new Bytes(bits); -} - -export function prepend(second, first) { - return append_builder(from_bit_array(first), second); -} - -export function append(first, second) { - return append_builder(first, from_bit_array(second)); -} - -export function concat_bit_arrays(bits) { - let _pipe = bits; - let _pipe$1 = $list.map(_pipe, (b) => { return from_bit_array(b); }); - return concat(_pipe$1); -} - -function to_list(loop$stack, loop$acc) { - while (true) { - let stack = loop$stack; - let acc = loop$acc; - if (stack.hasLength(0)) { - return acc; - } else if (stack.atLeastLength(1) && stack.head.hasLength(0)) { - let remaining_stack = stack.tail; - loop$stack = remaining_stack; - loop$acc = acc; - } else if (stack.atLeastLength(1) && - stack.head.atLeastLength(1) && - stack.head.head instanceof Bytes) { - let bits = stack.head.head[0]; - let rest = stack.head.tail; - let remaining_stack = stack.tail; - loop$stack = listPrepend(rest, remaining_stack); - loop$acc = listPrepend(bits, acc); - } else if (stack.atLeastLength(1) && - stack.head.atLeastLength(1) && - stack.head.head instanceof Text) { - let builder = stack.head.head[0]; - let rest = stack.head.tail; - let remaining_stack = stack.tail; - let bits = $bit_array.from_string($string_builder.to_string(builder)); - loop$stack = listPrepend(rest, remaining_stack); - loop$acc = listPrepend(bits, acc); - } else { - let builders = stack.head.head[0]; - let rest = stack.head.tail; - let remaining_stack = stack.tail; - loop$stack = listPrepend(builders, listPrepend(rest, remaining_stack)); - loop$acc = acc; - } - } -} - -export function to_bit_array(builder) { - let _pipe = toList([toList([builder])]); - let _pipe$1 = to_list(_pipe, toList([])); - let _pipe$2 = $list.reverse(_pipe$1); - return $bit_array.concat(_pipe$2); -} - -export function byte_size(builder) { - let _pipe = toList([toList([builder])]); - let _pipe$1 = to_list(_pipe, toList([])); - return $list.fold( - _pipe$1, - 0, - (acc, builder) => { return $bit_array.byte_size(builder) + acc; }, - ); -} diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/dict.mjs b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/dict.mjs deleted file mode 100644 index eeebcd912c0..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/dict.mjs +++ /dev/null @@ -1,285 +0,0 @@ -import { Error, toList, prepend as listPrepend, isEqual } from "../gleam.mjs"; -import * as $option from "../gleam/option.mjs"; -import { - map_size as size, - map_to_list as to_list, - new_map as do_new, - map_get as do_get, - map_insert as do_insert, - map_remove as do_delete, -} from "../gleam_stdlib.mjs"; - -export { size, to_list }; - -export function new$() { - return do_new(); -} - -export function is_empty(dict) { - return isEqual(dict, new$()); -} - -export function get(from, get) { - return do_get(from, get); -} - -function do_has_key(key, dict) { - return !isEqual(get(dict, key), new Error(undefined)); -} - -export function has_key(dict, key) { - return do_has_key(key, dict); -} - -export function insert(dict, key, value) { - return do_insert(key, value, dict); -} - -function fold_list_of_pair(loop$list, loop$initial) { - while (true) { - let list = loop$list; - let initial = loop$initial; - if (list.hasLength(0)) { - return initial; - } else { - let x = list.head; - let rest = list.tail; - loop$list = rest; - loop$initial = insert(initial, x[0], x[1]); - } - } -} - -export function from_list(list) { - return fold_list_of_pair(list, new$()); -} - -function reverse_and_concat(loop$remaining, loop$accumulator) { - while (true) { - let remaining = loop$remaining; - let accumulator = loop$accumulator; - if (remaining.hasLength(0)) { - return accumulator; - } else { - let item = remaining.head; - let rest = remaining.tail; - loop$remaining = rest; - loop$accumulator = listPrepend(item, accumulator); - } - } -} - -function do_keys_acc(loop$list, loop$acc) { - while (true) { - let list = loop$list; - let acc = loop$acc; - if (list.hasLength(0)) { - return reverse_and_concat(acc, toList([])); - } else { - let first = list.head; - let rest = list.tail; - loop$list = rest; - loop$acc = listPrepend(first[0], acc); - } - } -} - -function do_keys(dict) { - let list_of_pairs = to_list(dict); - return do_keys_acc(list_of_pairs, toList([])); -} - -export function keys(dict) { - return do_keys(dict); -} - -function do_values_acc(loop$list, loop$acc) { - while (true) { - let list = loop$list; - let acc = loop$acc; - if (list.hasLength(0)) { - return reverse_and_concat(acc, toList([])); - } else { - let first = list.head; - let rest = list.tail; - loop$list = rest; - loop$acc = listPrepend(first[1], acc); - } - } -} - -function do_values(dict) { - let list_of_pairs = to_list(dict); - return do_values_acc(list_of_pairs, toList([])); -} - -export function values(dict) { - return do_values(dict); -} - -function insert_taken(loop$dict, loop$desired_keys, loop$acc) { - while (true) { - let dict = loop$dict; - let desired_keys = loop$desired_keys; - let acc = loop$acc; - let insert$1 = (taken, key) => { - let $ = get(dict, key); - if ($.isOk()) { - let value = $[0]; - return insert(taken, key, value); - } else { - return taken; - } - }; - if (desired_keys.hasLength(0)) { - return acc; - } else { - let first = desired_keys.head; - let rest = desired_keys.tail; - loop$dict = dict; - loop$desired_keys = rest; - loop$acc = insert$1(acc, first); - } - } -} - -function do_take(desired_keys, dict) { - return insert_taken(dict, desired_keys, new$()); -} - -export function take(dict, desired_keys) { - return do_take(desired_keys, dict); -} - -function insert_pair(dict, pair) { - return insert(dict, pair[0], pair[1]); -} - -function fold_inserts(loop$new_entries, loop$dict) { - while (true) { - let new_entries = loop$new_entries; - let dict = loop$dict; - if (new_entries.hasLength(0)) { - return dict; - } else { - let first = new_entries.head; - let rest = new_entries.tail; - loop$new_entries = rest; - loop$dict = insert_pair(dict, first); - } - } -} - -function do_merge(dict, new_entries) { - let _pipe = new_entries; - let _pipe$1 = to_list(_pipe); - return fold_inserts(_pipe$1, dict); -} - -export function merge(dict, new_entries) { - return do_merge(dict, new_entries); -} - -export function delete$(dict, key) { - return do_delete(key, dict); -} - -export function drop(loop$dict, loop$disallowed_keys) { - while (true) { - let dict = loop$dict; - let disallowed_keys = loop$disallowed_keys; - if (disallowed_keys.hasLength(0)) { - return dict; - } else { - let first = disallowed_keys.head; - let rest = disallowed_keys.tail; - loop$dict = delete$(dict, first); - loop$disallowed_keys = rest; - } - } -} - -export function upsert(dict, key, fun) { - let _pipe = dict; - let _pipe$1 = get(_pipe, key); - let _pipe$2 = $option.from_result(_pipe$1); - let _pipe$3 = fun(_pipe$2); - return ((_capture) => { return insert(dict, key, _capture); })(_pipe$3); -} - -function do_fold(loop$list, loop$initial, loop$fun) { - while (true) { - let list = loop$list; - let initial = loop$initial; - let fun = loop$fun; - if (list.hasLength(0)) { - return initial; - } else { - let k = list.head[0]; - let v = list.head[1]; - let rest = list.tail; - loop$list = rest; - loop$initial = fun(initial, k, v); - loop$fun = fun; - } - } -} - -export function fold(dict, initial, fun) { - let _pipe = dict; - let _pipe$1 = to_list(_pipe); - return do_fold(_pipe$1, initial, fun); -} - -function do_map_values(f, dict) { - let f$1 = (dict, k, v) => { return insert(dict, k, f(k, v)); }; - return fold(dict, new$(), f$1); -} - -export function map_values(dict, fun) { - return do_map_values(fun, dict); -} - -function do_filter(f, dict) { - let insert$1 = (dict, k, v) => { - let $ = f(k, v); - if ($) { - return insert(dict, k, v); - } else { - return dict; - } - }; - let _pipe = dict; - return fold(_pipe, new$(), insert$1); -} - -export function filter(dict, predicate) { - return do_filter(predicate, dict); -} - -export function each(dict, fun) { - return fold( - dict, - undefined, - (nil, k, v) => { - fun(k, v); - return nil; - }, - ); -} - -export function combine(dict, other, fun) { - return fold( - dict, - other, - (acc, key, value) => { - let $ = get(acc, key); - if ($.isOk()) { - let other_value = $[0]; - return insert(acc, key, fun(value, other_value)); - } else { - return insert(acc, key, value); - } - }, - ); -} diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/dynamic.mjs b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/dynamic.mjs deleted file mode 100644 index 289fe15c58c..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/dynamic.mjs +++ /dev/null @@ -1,844 +0,0 @@ -import { Ok, Error, toList, prepend as listPrepend, CustomType as $CustomType } from "../gleam.mjs"; -import * as $bit_array from "../gleam/bit_array.mjs"; -import * as $dict from "../gleam/dict.mjs"; -import * as $int from "../gleam/int.mjs"; -import * as $list from "../gleam/list.mjs"; -import * as $option from "../gleam/option.mjs"; -import { Some } from "../gleam/option.mjs"; -import * as $result from "../gleam/result.mjs"; -import * as $string_builder from "../gleam/string_builder.mjs"; -import { - identity as from, - decode_bit_array, - classify_dynamic as do_classify, - decode_int, - decode_float, - decode_bool, - decode_list, - decode_result, - decode_option as decode_optional, - decode_field, - decode_tuple, - decode_tuple2, - decode_tuple3, - decode_tuple4, - decode_tuple5, - decode_tuple6, - tuple_get, - length as tuple_size, - decode_map, - decode_string, -} from "../gleam_stdlib.mjs"; - -export { from }; - -export class DecodeError extends $CustomType { - constructor(expected, found, path) { - super(); - this.expected = expected; - this.found = found; - this.path = path; - } -} - -export function dynamic(value) { - return new Ok(value); -} - -export function bit_array(data) { - return decode_bit_array(data); -} - -function put_expected(error, expected) { - return error.withFields({ expected: expected }); -} - -export function classify(data) { - return do_classify(data); -} - -export function int(data) { - return decode_int(data); -} - -export function float(data) { - return decode_float(data); -} - -export function bool(data) { - return decode_bool(data); -} - -export function shallow_list(value) { - return decode_list(value); -} - -export function optional(decode) { - return (value) => { return decode_optional(value, decode); }; -} - -function at_least_decode_tuple_error(size, data) { - let s = (() => { - if (size === 1) { - return ""; - } else { - return "s"; - } - })(); - let error = (() => { - let _pipe = toList([ - "Tuple of at least ", - $int.to_string(size), - " element", - s, - ]); - let _pipe$1 = $string_builder.from_strings(_pipe); - let _pipe$2 = $string_builder.to_string(_pipe$1); - return new DecodeError(_pipe$2, classify(data), toList([])); - })(); - return new Error(toList([error])); -} - -export function any(decoders) { - return (data) => { - if (decoders.hasLength(0)) { - return new Error( - toList([new DecodeError("another type", classify(data), toList([]))]), - ); - } else { - let decoder = decoders.head; - let decoders$1 = decoders.tail; - let $ = decoder(data); - if ($.isOk()) { - let decoded = $[0]; - return new Ok(decoded); - } else { - return any(decoders$1)(data); - } - } - }; -} - -function all_errors(result) { - if (result.isOk()) { - return toList([]); - } else { - let errors = result[0]; - return errors; - } -} - -export function decode1(constructor, t1) { - return (value) => { - let $ = t1(value); - if ($.isOk()) { - let a = $[0]; - return new Ok(constructor(a)); - } else { - let a = $; - return new Error(all_errors(a)); - } - }; -} - -function push_path(error, name) { - let name$1 = from(name); - let decoder = any( - toList([string, (x) => { return $result.map(int(x), $int.to_string); }]), - ); - let name$2 = (() => { - let $ = decoder(name$1); - if ($.isOk()) { - let name$2 = $[0]; - return name$2; - } else { - let _pipe = toList(["<", classify(name$1), ">"]); - let _pipe$1 = $string_builder.from_strings(_pipe); - return $string_builder.to_string(_pipe$1); - } - })(); - return error.withFields({ path: listPrepend(name$2, error.path) }); -} - -export function result(decode_ok, decode_error) { - return (value) => { - return $result.try$( - decode_result(value), - (inner_result) => { - if (inner_result.isOk()) { - let raw = inner_result[0]; - return $result.try$( - (() => { - let _pipe = decode_ok(raw); - return map_errors( - _pipe, - (_capture) => { return push_path(_capture, "ok"); }, - ); - })(), - (value) => { return new Ok(new Ok(value)); }, - ); - } else { - let raw = inner_result[0]; - return $result.try$( - (() => { - let _pipe = decode_error(raw); - return map_errors( - _pipe, - (_capture) => { return push_path(_capture, "error"); }, - ); - })(), - (value) => { return new Ok(new Error(value)); }, - ); - } - }, - ); - }; -} - -export function list(decoder_type) { - return (dynamic) => { - return $result.try$( - shallow_list(dynamic), - (list) => { - let _pipe = list; - let _pipe$1 = $list.try_map(_pipe, decoder_type); - return map_errors( - _pipe$1, - (_capture) => { return push_path(_capture, "*"); }, - ); - }, - ); - }; -} - -function map_errors(result, f) { - return $result.map_error( - result, - (_capture) => { return $list.map(_capture, f); }, - ); -} - -export function string(data) { - return decode_string(data); -} - -export function field(name, inner_type) { - return (value) => { - let missing_field_error = new DecodeError("field", "nothing", toList([])); - return $result.try$( - decode_field(value, name), - (maybe_inner) => { - let _pipe = maybe_inner; - let _pipe$1 = $option.to_result(_pipe, toList([missing_field_error])); - let _pipe$2 = $result.try$(_pipe$1, inner_type); - return map_errors( - _pipe$2, - (_capture) => { return push_path(_capture, name); }, - ); - }, - ); - }; -} - -export function optional_field(name, inner_type) { - return (value) => { - return $result.try$( - decode_field(value, name), - (maybe_inner) => { - if (maybe_inner instanceof $option.None) { - return new Ok(new $option.None()); - } else { - let dynamic_inner = maybe_inner[0]; - let _pipe = inner_type(dynamic_inner); - let _pipe$1 = $result.map(_pipe, (var0) => { return new Some(var0); }); - return map_errors( - _pipe$1, - (_capture) => { return push_path(_capture, name); }, - ); - } - }, - ); - }; -} - -export function element(index, inner_type) { - return (data) => { - return $result.try$( - decode_tuple(data), - (tuple) => { - let size = tuple_size(tuple); - return $result.try$( - (() => { - let $ = index >= 0; - if ($) { - let $1 = index < size; - if ($1) { - return tuple_get(tuple, index); - } else { - return at_least_decode_tuple_error(index + 1, data); - } - } else { - let $1 = $int.absolute_value(index) <= size; - if ($1) { - return tuple_get(tuple, size + index); - } else { - return at_least_decode_tuple_error( - $int.absolute_value(index), - data, - ); - } - } - })(), - (data) => { - let _pipe = inner_type(data); - return map_errors( - _pipe, - (_capture) => { return push_path(_capture, index); }, - ); - }, - ); - }, - ); - }; -} - -function tuple_errors(result, name) { - if (result.isOk()) { - return toList([]); - } else { - let errors = result[0]; - return $list.map( - errors, - (_capture) => { return push_path(_capture, name); }, - ); - } -} - -export function tuple2(decode1, decode2) { - return (value) => { - return $result.try$( - decode_tuple2(value), - (_use0) => { - let a = _use0[0]; - let b = _use0[1]; - let $ = decode1(a); - let $1 = decode2(b); - if ($.isOk() && $1.isOk()) { - let a$1 = $[0]; - let b$1 = $1[0]; - return new Ok([a$1, b$1]); - } else { - let a$1 = $; - let b$1 = $1; - let _pipe = tuple_errors(a$1, "0"); - let _pipe$1 = $list.append(_pipe, tuple_errors(b$1, "1")); - return new Error(_pipe$1); - } - }, - ); - }; -} - -export function tuple3(decode1, decode2, decode3) { - return (value) => { - return $result.try$( - decode_tuple3(value), - (_use0) => { - let a = _use0[0]; - let b = _use0[1]; - let c = _use0[2]; - let $ = decode1(a); - let $1 = decode2(b); - let $2 = decode3(c); - if ($.isOk() && $1.isOk() && $2.isOk()) { - let a$1 = $[0]; - let b$1 = $1[0]; - let c$1 = $2[0]; - return new Ok([a$1, b$1, c$1]); - } else { - let a$1 = $; - let b$1 = $1; - let c$1 = $2; - let _pipe = tuple_errors(a$1, "0"); - let _pipe$1 = $list.append(_pipe, tuple_errors(b$1, "1")); - let _pipe$2 = $list.append(_pipe$1, tuple_errors(c$1, "2")); - return new Error(_pipe$2); - } - }, - ); - }; -} - -export function tuple4(decode1, decode2, decode3, decode4) { - return (value) => { - return $result.try$( - decode_tuple4(value), - (_use0) => { - let a = _use0[0]; - let b = _use0[1]; - let c = _use0[2]; - let d = _use0[3]; - let $ = decode1(a); - let $1 = decode2(b); - let $2 = decode3(c); - let $3 = decode4(d); - if ($.isOk() && $1.isOk() && $2.isOk() && $3.isOk()) { - let a$1 = $[0]; - let b$1 = $1[0]; - let c$1 = $2[0]; - let d$1 = $3[0]; - return new Ok([a$1, b$1, c$1, d$1]); - } else { - let a$1 = $; - let b$1 = $1; - let c$1 = $2; - let d$1 = $3; - let _pipe = tuple_errors(a$1, "0"); - let _pipe$1 = $list.append(_pipe, tuple_errors(b$1, "1")); - let _pipe$2 = $list.append(_pipe$1, tuple_errors(c$1, "2")); - let _pipe$3 = $list.append(_pipe$2, tuple_errors(d$1, "3")); - return new Error(_pipe$3); - } - }, - ); - }; -} - -export function tuple5(decode1, decode2, decode3, decode4, decode5) { - return (value) => { - return $result.try$( - decode_tuple5(value), - (_use0) => { - let a = _use0[0]; - let b = _use0[1]; - let c = _use0[2]; - let d = _use0[3]; - let e = _use0[4]; - let $ = decode1(a); - let $1 = decode2(b); - let $2 = decode3(c); - let $3 = decode4(d); - let $4 = decode5(e); - if ($.isOk() && $1.isOk() && $2.isOk() && $3.isOk() && $4.isOk()) { - let a$1 = $[0]; - let b$1 = $1[0]; - let c$1 = $2[0]; - let d$1 = $3[0]; - let e$1 = $4[0]; - return new Ok([a$1, b$1, c$1, d$1, e$1]); - } else { - let a$1 = $; - let b$1 = $1; - let c$1 = $2; - let d$1 = $3; - let e$1 = $4; - let _pipe = tuple_errors(a$1, "0"); - let _pipe$1 = $list.append(_pipe, tuple_errors(b$1, "1")); - let _pipe$2 = $list.append(_pipe$1, tuple_errors(c$1, "2")); - let _pipe$3 = $list.append(_pipe$2, tuple_errors(d$1, "3")); - let _pipe$4 = $list.append(_pipe$3, tuple_errors(e$1, "4")); - return new Error(_pipe$4); - } - }, - ); - }; -} - -export function tuple6(decode1, decode2, decode3, decode4, decode5, decode6) { - return (value) => { - return $result.try$( - decode_tuple6(value), - (_use0) => { - let a = _use0[0]; - let b = _use0[1]; - let c = _use0[2]; - let d = _use0[3]; - let e = _use0[4]; - let f = _use0[5]; - let $ = decode1(a); - let $1 = decode2(b); - let $2 = decode3(c); - let $3 = decode4(d); - let $4 = decode5(e); - let $5 = decode6(f); - if ($.isOk() && - $1.isOk() && - $2.isOk() && - $3.isOk() && - $4.isOk() && - $5.isOk()) { - let a$1 = $[0]; - let b$1 = $1[0]; - let c$1 = $2[0]; - let d$1 = $3[0]; - let e$1 = $4[0]; - let f$1 = $5[0]; - return new Ok([a$1, b$1, c$1, d$1, e$1, f$1]); - } else { - let a$1 = $; - let b$1 = $1; - let c$1 = $2; - let d$1 = $3; - let e$1 = $4; - let f$1 = $5; - let _pipe = tuple_errors(a$1, "0"); - let _pipe$1 = $list.append(_pipe, tuple_errors(b$1, "1")); - let _pipe$2 = $list.append(_pipe$1, tuple_errors(c$1, "2")); - let _pipe$3 = $list.append(_pipe$2, tuple_errors(d$1, "3")); - let _pipe$4 = $list.append(_pipe$3, tuple_errors(e$1, "4")); - let _pipe$5 = $list.append(_pipe$4, tuple_errors(f$1, "5")); - return new Error(_pipe$5); - } - }, - ); - }; -} - -export function dict(key_type, value_type) { - return (value) => { - return $result.try$( - decode_map(value), - (map) => { - return $result.try$( - (() => { - let _pipe = map; - let _pipe$1 = $dict.to_list(_pipe); - return $list.try_map( - _pipe$1, - (pair) => { - let k = pair[0]; - let v = pair[1]; - return $result.try$( - (() => { - let _pipe$2 = key_type(k); - return map_errors( - _pipe$2, - (_capture) => { return push_path(_capture, "keys"); }, - ); - })(), - (k) => { - return $result.try$( - (() => { - let _pipe$2 = value_type(v); - return map_errors( - _pipe$2, - (_capture) => { return push_path(_capture, "values"); }, - ); - })(), - (v) => { return new Ok([k, v]); }, - ); - }, - ); - }, - ); - })(), - (pairs) => { return new Ok($dict.from_list(pairs)); }, - ); - }, - ); - }; -} - -export function decode2(constructor, t1, t2) { - return (value) => { - let $ = t1(value); - let $1 = t2(value); - if ($.isOk() && $1.isOk()) { - let a = $[0]; - let b = $1[0]; - return new Ok(constructor(a, b)); - } else { - let a = $; - let b = $1; - return new Error($list.flatten(toList([all_errors(a), all_errors(b)]))); - } - }; -} - -export function decode3(constructor, t1, t2, t3) { - return (value) => { - let $ = t1(value); - let $1 = t2(value); - let $2 = t3(value); - if ($.isOk() && $1.isOk() && $2.isOk()) { - let a = $[0]; - let b = $1[0]; - let c = $2[0]; - return new Ok(constructor(a, b, c)); - } else { - let a = $; - let b = $1; - let c = $2; - return new Error( - $list.flatten(toList([all_errors(a), all_errors(b), all_errors(c)])), - ); - } - }; -} - -export function decode4(constructor, t1, t2, t3, t4) { - return (x) => { - let $ = t1(x); - let $1 = t2(x); - let $2 = t3(x); - let $3 = t4(x); - if ($.isOk() && $1.isOk() && $2.isOk() && $3.isOk()) { - let a = $[0]; - let b = $1[0]; - let c = $2[0]; - let d = $3[0]; - return new Ok(constructor(a, b, c, d)); - } else { - let a = $; - let b = $1; - let c = $2; - let d = $3; - return new Error( - $list.flatten( - toList([all_errors(a), all_errors(b), all_errors(c), all_errors(d)]), - ), - ); - } - }; -} - -export function decode5(constructor, t1, t2, t3, t4, t5) { - return (x) => { - let $ = t1(x); - let $1 = t2(x); - let $2 = t3(x); - let $3 = t4(x); - let $4 = t5(x); - if ($.isOk() && $1.isOk() && $2.isOk() && $3.isOk() && $4.isOk()) { - let a = $[0]; - let b = $1[0]; - let c = $2[0]; - let d = $3[0]; - let e = $4[0]; - return new Ok(constructor(a, b, c, d, e)); - } else { - let a = $; - let b = $1; - let c = $2; - let d = $3; - let e = $4; - return new Error( - $list.flatten( - toList([ - all_errors(a), - all_errors(b), - all_errors(c), - all_errors(d), - all_errors(e), - ]), - ), - ); - } - }; -} - -export function decode6(constructor, t1, t2, t3, t4, t5, t6) { - return (x) => { - let $ = t1(x); - let $1 = t2(x); - let $2 = t3(x); - let $3 = t4(x); - let $4 = t5(x); - let $5 = t6(x); - if ($.isOk() && - $1.isOk() && - $2.isOk() && - $3.isOk() && - $4.isOk() && - $5.isOk()) { - let a = $[0]; - let b = $1[0]; - let c = $2[0]; - let d = $3[0]; - let e = $4[0]; - let f = $5[0]; - return new Ok(constructor(a, b, c, d, e, f)); - } else { - let a = $; - let b = $1; - let c = $2; - let d = $3; - let e = $4; - let f = $5; - return new Error( - $list.flatten( - toList([ - all_errors(a), - all_errors(b), - all_errors(c), - all_errors(d), - all_errors(e), - all_errors(f), - ]), - ), - ); - } - }; -} - -export function decode7(constructor, t1, t2, t3, t4, t5, t6, t7) { - return (x) => { - let $ = t1(x); - let $1 = t2(x); - let $2 = t3(x); - let $3 = t4(x); - let $4 = t5(x); - let $5 = t6(x); - let $6 = t7(x); - if ($.isOk() && - $1.isOk() && - $2.isOk() && - $3.isOk() && - $4.isOk() && - $5.isOk() && - $6.isOk()) { - let a = $[0]; - let b = $1[0]; - let c = $2[0]; - let d = $3[0]; - let e = $4[0]; - let f = $5[0]; - let g = $6[0]; - return new Ok(constructor(a, b, c, d, e, f, g)); - } else { - let a = $; - let b = $1; - let c = $2; - let d = $3; - let e = $4; - let f = $5; - let g = $6; - return new Error( - $list.flatten( - toList([ - all_errors(a), - all_errors(b), - all_errors(c), - all_errors(d), - all_errors(e), - all_errors(f), - all_errors(g), - ]), - ), - ); - } - }; -} - -export function decode8(constructor, t1, t2, t3, t4, t5, t6, t7, t8) { - return (x) => { - let $ = t1(x); - let $1 = t2(x); - let $2 = t3(x); - let $3 = t4(x); - let $4 = t5(x); - let $5 = t6(x); - let $6 = t7(x); - let $7 = t8(x); - if ($.isOk() && - $1.isOk() && - $2.isOk() && - $3.isOk() && - $4.isOk() && - $5.isOk() && - $6.isOk() && - $7.isOk()) { - let a = $[0]; - let b = $1[0]; - let c = $2[0]; - let d = $3[0]; - let e = $4[0]; - let f = $5[0]; - let g = $6[0]; - let h = $7[0]; - return new Ok(constructor(a, b, c, d, e, f, g, h)); - } else { - let a = $; - let b = $1; - let c = $2; - let d = $3; - let e = $4; - let f = $5; - let g = $6; - let h = $7; - return new Error( - $list.flatten( - toList([ - all_errors(a), - all_errors(b), - all_errors(c), - all_errors(d), - all_errors(e), - all_errors(f), - all_errors(g), - all_errors(h), - ]), - ), - ); - } - }; -} - -export function decode9(constructor, t1, t2, t3, t4, t5, t6, t7, t8, t9) { - return (x) => { - let $ = t1(x); - let $1 = t2(x); - let $2 = t3(x); - let $3 = t4(x); - let $4 = t5(x); - let $5 = t6(x); - let $6 = t7(x); - let $7 = t8(x); - let $8 = t9(x); - if ($.isOk() && - $1.isOk() && - $2.isOk() && - $3.isOk() && - $4.isOk() && - $5.isOk() && - $6.isOk() && - $7.isOk() && - $8.isOk()) { - let a = $[0]; - let b = $1[0]; - let c = $2[0]; - let d = $3[0]; - let e = $4[0]; - let f = $5[0]; - let g = $6[0]; - let h = $7[0]; - let i = $8[0]; - return new Ok(constructor(a, b, c, d, e, f, g, h, i)); - } else { - let a = $; - let b = $1; - let c = $2; - let d = $3; - let e = $4; - let f = $5; - let g = $6; - let h = $7; - let i = $8; - return new Error( - $list.flatten( - toList([ - all_errors(a), - all_errors(b), - all_errors(c), - all_errors(d), - all_errors(e), - all_errors(f), - all_errors(g), - all_errors(h), - all_errors(i), - ]), - ), - ); - } - }; -} diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/float.mjs b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/float.mjs deleted file mode 100644 index 5ac51612ce2..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/float.mjs +++ /dev/null @@ -1,205 +0,0 @@ -import { Ok, Error, divideFloat } from "../gleam.mjs"; -import * as $order from "../gleam/order.mjs"; -import { - parse_float as do_parse, - float_to_string as do_to_string, - ceiling as do_ceiling, - floor as do_floor, - round as js_round, - truncate as do_truncate, - identity as do_to_float, - power as do_power, - random_uniform as random, -} from "../gleam_stdlib.mjs"; - -export { random }; - -export function parse(string) { - return do_parse(string); -} - -export function to_string(x) { - return do_to_string(x); -} - -export function compare(a, b) { - let $ = a === b; - if ($) { - return new $order.Eq(); - } else { - let $1 = a < b; - if ($1) { - return new $order.Lt(); - } else { - return new $order.Gt(); - } - } -} - -export function min(a, b) { - let $ = a < b; - if ($) { - return a; - } else { - return b; - } -} - -export function max(a, b) { - let $ = a > b; - if ($) { - return a; - } else { - return b; - } -} - -export function clamp(x, min_bound, max_bound) { - let _pipe = x; - let _pipe$1 = min(_pipe, max_bound); - return max(_pipe$1, min_bound); -} - -export function ceiling(x) { - return do_ceiling(x); -} - -export function floor(x) { - return do_floor(x); -} - -export function truncate(x) { - return do_truncate(x); -} - -export function absolute_value(x) { - let $ = x >= 0.0; - if ($) { - return x; - } else { - return 0.0 - x; - } -} - -export function loosely_compare(a, b, tolerance) { - let difference = absolute_value(a - b); - let $ = difference <= tolerance; - if ($) { - return new $order.Eq(); - } else { - return compare(a, b); - } -} - -export function loosely_equals(a, b, tolerance) { - let difference = absolute_value(a - b); - return difference <= tolerance; -} - -export function power(base, exponent) { - let fractional = (ceiling(exponent) - exponent) > 0.0; - let $ = ((base < 0.0) && fractional) || ((base === 0.0) && (exponent < 0.0)); - if ($) { - return new Error(undefined); - } else { - return new Ok(do_power(base, exponent)); - } -} - -export function square_root(x) { - return power(x, 0.5); -} - -export function negate(x) { - return -1.0 * x; -} - -function do_round(x) { - let $ = x >= 0.0; - if ($) { - return js_round(x); - } else { - return 0 - js_round(negate(x)); - } -} - -export function round(x) { - return do_round(x); -} - -export function to_precision(x, precision) { - let factor = do_power(10.0, do_to_float(- precision)); - return do_to_float(round(divideFloat(x, factor))) * factor; -} - -function do_sum(loop$numbers, loop$initial) { - while (true) { - let numbers = loop$numbers; - let initial = loop$initial; - if (numbers.hasLength(0)) { - return initial; - } else { - let x = numbers.head; - let rest = numbers.tail; - loop$numbers = rest; - loop$initial = x + initial; - } - } -} - -export function sum(numbers) { - let _pipe = numbers; - return do_sum(_pipe, 0.0); -} - -function do_product(loop$numbers, loop$initial) { - while (true) { - let numbers = loop$numbers; - let initial = loop$initial; - if (numbers.hasLength(0)) { - return initial; - } else { - let x = numbers.head; - let rest = numbers.tail; - loop$numbers = rest; - loop$initial = x * initial; - } - } -} - -export function product(numbers) { - if (numbers.hasLength(0)) { - return 1.0; - } else { - return do_product(numbers, 1.0); - } -} - -export function modulo(dividend, divisor) { - if (divisor === 0.0) { - return new Error(undefined); - } else { - return new Ok(dividend - (floor(divideFloat(dividend, divisor)) * divisor)); - } -} - -export function divide(a, b) { - if (b === 0.0) { - return new Error(undefined); - } else { - let b$1 = b; - return new Ok(divideFloat(a, b$1)); - } -} - -export function add(a, b) { - return a + b; -} - -export function multiply(a, b) { - return a * b; -} - -export function subtract(a, b) { - return a - b; -} diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/function.mjs b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/function.mjs deleted file mode 100644 index a6bafc55a3a..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/function.mjs +++ /dev/null @@ -1,70 +0,0 @@ -export function compose(fun1, fun2) { - return (a) => { return fun2(fun1(a)); }; -} - -export function curry2(fun) { - return (a) => { return (b) => { return fun(a, b); }; }; -} - -export function curry3(fun) { - return (a) => { return (b) => { return (c) => { return fun(a, b, c); }; }; }; -} - -export function curry4(fun) { - return (a) => { - return (b) => { - return (c) => { return (d) => { return fun(a, b, c, d); }; }; - }; - }; -} - -export function curry5(fun) { - return (a) => { - return (b) => { - return (c) => { - return (d) => { return (e) => { return fun(a, b, c, d, e); }; }; - }; - }; - }; -} - -export function curry6(fun) { - return (a) => { - return (b) => { - return (c) => { - return (d) => { - return (e) => { return (f) => { return fun(a, b, c, d, e, f); }; }; - }; - }; - }; - }; -} - -export function flip(fun) { - return (b, a) => { return fun(a, b); }; -} - -export function identity(x) { - return x; -} - -export function constant(value) { - return (_) => { return value; }; -} - -export function tap(arg, effect) { - effect(arg); - return arg; -} - -export function apply1(fun, arg1) { - return fun(arg1); -} - -export function apply2(fun, arg1, arg2) { - return fun(arg1, arg2); -} - -export function apply3(fun, arg1, arg2, arg3) { - return fun(arg1, arg2, arg3); -} diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/int.mjs b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/int.mjs deleted file mode 100644 index 42b7adb8f4e..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/int.mjs +++ /dev/null @@ -1,303 +0,0 @@ -import { Ok, Error, toList, prepend as listPrepend, remainderInt, divideInt } from "../gleam.mjs"; -import * as $float from "../gleam/float.mjs"; -import * as $order from "../gleam/order.mjs"; -import { - parse_int as do_parse, - int_from_base_string as do_base_parse, - to_string as do_to_string, - int_to_base_string as do_to_base_string, - identity as do_to_float, - bitwise_and, - bitwise_not, - bitwise_or, - bitwise_exclusive_or, - bitwise_shift_left, - bitwise_shift_right, -} from "../gleam_stdlib.mjs"; - -export { - bitwise_and, - bitwise_exclusive_or, - bitwise_not, - bitwise_or, - bitwise_shift_left, - bitwise_shift_right, -}; - -export function absolute_value(x) { - let $ = x >= 0; - if ($) { - return x; - } else { - return x * -1; - } -} - -export function parse(string) { - return do_parse(string); -} - -export function base_parse(string, base) { - let $ = (base >= 2) && (base <= 36); - if ($) { - return do_base_parse(string, base); - } else { - return new Error(undefined); - } -} - -export function to_string(x) { - return do_to_string(x); -} - -export function to_base_string(x, base) { - let $ = (base >= 2) && (base <= 36); - if ($) { - return new Ok(do_to_base_string(x, base)); - } else { - return new Error(undefined); - } -} - -export function to_base2(x) { - return do_to_base_string(x, 2); -} - -export function to_base8(x) { - return do_to_base_string(x, 8); -} - -export function to_base16(x) { - return do_to_base_string(x, 16); -} - -export function to_base36(x) { - return do_to_base_string(x, 36); -} - -export function to_float(x) { - return do_to_float(x); -} - -export function power(base, exponent) { - let _pipe = base; - let _pipe$1 = to_float(_pipe); - return $float.power(_pipe$1, exponent); -} - -export function square_root(x) { - let _pipe = x; - let _pipe$1 = to_float(_pipe); - return $float.square_root(_pipe$1); -} - -export function compare(a, b) { - let $ = a === b; - if ($) { - return new $order.Eq(); - } else { - let $1 = a < b; - if ($1) { - return new $order.Lt(); - } else { - return new $order.Gt(); - } - } -} - -export function min(a, b) { - let $ = a < b; - if ($) { - return a; - } else { - return b; - } -} - -export function max(a, b) { - let $ = a > b; - if ($) { - return a; - } else { - return b; - } -} - -export function clamp(x, min_bound, max_bound) { - let _pipe = x; - let _pipe$1 = min(_pipe, max_bound); - return max(_pipe$1, min_bound); -} - -export function is_even(x) { - return (remainderInt(x, 2)) === 0; -} - -export function is_odd(x) { - return (remainderInt(x, 2)) !== 0; -} - -export function negate(x) { - return -1 * x; -} - -function do_sum(loop$numbers, loop$initial) { - while (true) { - let numbers = loop$numbers; - let initial = loop$initial; - if (numbers.hasLength(0)) { - return initial; - } else { - let x = numbers.head; - let rest = numbers.tail; - loop$numbers = rest; - loop$initial = x + initial; - } - } -} - -export function sum(numbers) { - let _pipe = numbers; - return do_sum(_pipe, 0); -} - -function do_product(loop$numbers, loop$initial) { - while (true) { - let numbers = loop$numbers; - let initial = loop$initial; - if (numbers.hasLength(0)) { - return initial; - } else { - let x = numbers.head; - let rest = numbers.tail; - loop$numbers = rest; - loop$initial = x * initial; - } - } -} - -export function product(numbers) { - if (numbers.hasLength(0)) { - return 1; - } else { - return do_product(numbers, 1); - } -} - -function do_digits(loop$x, loop$base, loop$acc) { - while (true) { - let x = loop$x; - let base = loop$base; - let acc = loop$acc; - let $ = absolute_value(x) < base; - if ($) { - return listPrepend(x, acc); - } else { - loop$x = divideInt(x, base); - loop$base = base; - loop$acc = listPrepend(remainderInt(x, base), acc); - } - } -} - -export function digits(x, base) { - let $ = base < 2; - if ($) { - return new Error(undefined); - } else { - return new Ok(do_digits(x, base, toList([]))); - } -} - -function do_undigits(loop$numbers, loop$base, loop$acc) { - while (true) { - let numbers = loop$numbers; - let base = loop$base; - let acc = loop$acc; - if (numbers.hasLength(0)) { - return new Ok(acc); - } else if (numbers.atLeastLength(1) && (numbers.head >= base)) { - let digit = numbers.head; - return new Error(undefined); - } else { - let digit = numbers.head; - let rest = numbers.tail; - loop$numbers = rest; - loop$base = base; - loop$acc = acc * base + digit; - } - } -} - -export function undigits(numbers, base) { - let $ = base < 2; - if ($) { - return new Error(undefined); - } else { - return do_undigits(numbers, base, 0); - } -} - -export function random(max) { - let _pipe = ($float.random() * to_float(max)); - let _pipe$1 = $float.floor(_pipe); - return $float.round(_pipe$1); -} - -export function divide(dividend, divisor) { - if (divisor === 0) { - return new Error(undefined); - } else { - let divisor$1 = divisor; - return new Ok(divideInt(dividend, divisor$1)); - } -} - -export function remainder(dividend, divisor) { - if (divisor === 0) { - return new Error(undefined); - } else { - let divisor$1 = divisor; - return new Ok(remainderInt(dividend, divisor$1)); - } -} - -export function modulo(dividend, divisor) { - if (divisor === 0) { - return new Error(undefined); - } else { - let remainder$1 = remainderInt(dividend, divisor); - let $ = remainder$1 * divisor < 0; - if ($) { - return new Ok(remainder$1 + divisor); - } else { - return new Ok(remainder$1); - } - } -} - -export function floor_divide(dividend, divisor) { - if (divisor === 0) { - return new Error(undefined); - } else { - let divisor$1 = divisor; - let $ = (dividend * divisor$1 < 0) && ((remainderInt(dividend, divisor$1)) !== 0); - if ($) { - return new Ok((divideInt(dividend, divisor$1)) - 1); - } else { - return new Ok(divideInt(dividend, divisor$1)); - } - } -} - -export function add(a, b) { - return a + b; -} - -export function multiply(a, b) { - return a * b; -} - -export function subtract(a, b) { - return a - b; -} diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/io.mjs b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/io.mjs deleted file mode 100644 index 46d09446d0e..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/io.mjs +++ /dev/null @@ -1,31 +0,0 @@ -import * as $string from "../gleam/string.mjs"; -import { - print as do_print, - print_error as do_print_error, - console_log as do_println, - console_error as do_println_error, - print_debug as do_debug_println, -} from "../gleam_stdlib.mjs"; - -export function print(string) { - return do_print(string); -} - -export function print_error(string) { - return do_print_error(string); -} - -export function println(string) { - return do_println(string); -} - -export function println_error(string) { - return do_println_error(string); -} - -export function debug(term) { - let _pipe = term; - let _pipe$1 = $string.inspect(_pipe); - do_debug_println(_pipe$1) - return term; -} diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/iterator.mjs b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/iterator.mjs deleted file mode 100644 index ab75e18aa1c..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/iterator.mjs +++ /dev/null @@ -1,969 +0,0 @@ -import { - Ok, - Error, - toList, - prepend as listPrepend, - CustomType as $CustomType, - isEqual, -} from "../gleam.mjs"; -import * as $dict from "../gleam/dict.mjs"; -import * as $int from "../gleam/int.mjs"; -import * as $list from "../gleam/list.mjs"; -import * as $option from "../gleam/option.mjs"; -import { None, Some } from "../gleam/option.mjs"; -import * as $order from "../gleam/order.mjs"; - -class Stop extends $CustomType {} - -class Continue extends $CustomType { - constructor(x0, x1) { - super(); - this[0] = x0; - this[1] = x1; - } -} - -class Iterator extends $CustomType { - constructor(continuation) { - super(); - this.continuation = continuation; - } -} - -export class Next extends $CustomType { - constructor(element, accumulator) { - super(); - this.element = element; - this.accumulator = accumulator; - } -} - -export class Done extends $CustomType {} - -class AnotherBy extends $CustomType { - constructor(x0, x1, x2, x3) { - super(); - this[0] = x0; - this[1] = x1; - this[2] = x2; - this[3] = x3; - } -} - -class LastBy extends $CustomType { - constructor(x0) { - super(); - this[0] = x0; - } -} - -class Another extends $CustomType { - constructor(x0, x1) { - super(); - this[0] = x0; - this[1] = x1; - } -} - -class Last extends $CustomType { - constructor(x0) { - super(); - this[0] = x0; - } -} - -class NoMore extends $CustomType {} - -function stop() { - return new Stop(); -} - -function do_unfold(initial, f) { - return () => { - let $ = f(initial); - if ($ instanceof Next) { - let x = $.element; - let acc = $.accumulator; - return new Continue(x, do_unfold(acc, f)); - } else { - return new Stop(); - } - }; -} - -export function unfold(initial, f) { - let _pipe = initial; - let _pipe$1 = do_unfold(_pipe, f); - return new Iterator(_pipe$1); -} - -export function repeatedly(f) { - return unfold(undefined, (_) => { return new Next(f(), undefined); }); -} - -export function repeat(x) { - return repeatedly(() => { return x; }); -} - -export function from_list(list) { - let yield$1 = (acc) => { - if (acc.hasLength(0)) { - return new Done(); - } else { - let head = acc.head; - let tail = acc.tail; - return new Next(head, tail); - } - }; - return unfold(list, yield$1); -} - -function do_transform(continuation, state, f) { - return () => { - let $ = continuation(); - if ($ instanceof Stop) { - return new Stop(); - } else { - let el = $[0]; - let next = $[1]; - let $1 = f(state, el); - if ($1 instanceof Done) { - return new Stop(); - } else { - let yield$1 = $1.element; - let next_state = $1.accumulator; - return new Continue(yield$1, do_transform(next, next_state, f)); - } - } - }; -} - -export function transform(iterator, initial, f) { - let _pipe = do_transform(iterator.continuation, initial, f); - return new Iterator(_pipe); -} - -function do_fold(loop$continuation, loop$f, loop$accumulator) { - while (true) { - let continuation = loop$continuation; - let f = loop$f; - let accumulator = loop$accumulator; - let $ = continuation(); - if ($ instanceof Continue) { - let elem = $[0]; - let next = $[1]; - loop$continuation = next; - loop$f = f; - loop$accumulator = f(accumulator, elem); - } else { - return accumulator; - } - } -} - -export function fold(iterator, initial, f) { - let _pipe = iterator.continuation; - return do_fold(_pipe, f, initial); -} - -export function run(iterator) { - return fold(iterator, undefined, (_, _1) => { return undefined; }); -} - -export function to_list(iterator) { - let _pipe = iterator; - let _pipe$1 = fold( - _pipe, - toList([]), - (acc, e) => { return listPrepend(e, acc); }, - ); - return $list.reverse(_pipe$1); -} - -export function step(iterator) { - let $ = iterator.continuation(); - if ($ instanceof Stop) { - return new Done(); - } else { - let e = $[0]; - let a = $[1]; - return new Next(e, new Iterator(a)); - } -} - -function do_take(continuation, desired) { - return () => { - let $ = desired > 0; - if (!$) { - return new Stop(); - } else { - let $1 = continuation(); - if ($1 instanceof Stop) { - return new Stop(); - } else { - let e = $1[0]; - let next = $1[1]; - return new Continue(e, do_take(next, desired - 1)); - } - } - }; -} - -export function take(iterator, desired) { - let _pipe = iterator.continuation; - let _pipe$1 = do_take(_pipe, desired); - return new Iterator(_pipe$1); -} - -function do_drop(loop$continuation, loop$desired) { - while (true) { - let continuation = loop$continuation; - let desired = loop$desired; - let $ = continuation(); - if ($ instanceof Stop) { - return new Stop(); - } else { - let e = $[0]; - let next = $[1]; - let $1 = desired > 0; - if ($1) { - loop$continuation = next; - loop$desired = desired - 1; - } else { - return new Continue(e, next); - } - } - } -} - -export function drop(iterator, desired) { - let _pipe = () => { return do_drop(iterator.continuation, desired); }; - return new Iterator(_pipe); -} - -function do_map(continuation, f) { - return () => { - let $ = continuation(); - if ($ instanceof Stop) { - return new Stop(); - } else { - let e = $[0]; - let continuation$1 = $[1]; - return new Continue(f(e), do_map(continuation$1, f)); - } - }; -} - -export function map(iterator, f) { - let _pipe = iterator.continuation; - let _pipe$1 = do_map(_pipe, f); - return new Iterator(_pipe$1); -} - -function do_map2(continuation1, continuation2, fun) { - return () => { - let $ = continuation1(); - if ($ instanceof Stop) { - return new Stop(); - } else { - let a = $[0]; - let next_a = $[1]; - let $1 = continuation2(); - if ($1 instanceof Stop) { - return new Stop(); - } else { - let b = $1[0]; - let next_b = $1[1]; - return new Continue(fun(a, b), do_map2(next_a, next_b, fun)); - } - } - }; -} - -export function map2(iterator1, iterator2, fun) { - let _pipe = do_map2(iterator1.continuation, iterator2.continuation, fun); - return new Iterator(_pipe); -} - -function do_append(first, second) { - let $ = first(); - if ($ instanceof Continue) { - let e = $[0]; - let first$1 = $[1]; - return new Continue(e, () => { return do_append(first$1, second); }); - } else { - return second(); - } -} - -export function append(first, second) { - let _pipe = () => { - return do_append(first.continuation, second.continuation); - }; - return new Iterator(_pipe); -} - -function do_flatten(flattened) { - let $ = flattened(); - if ($ instanceof Stop) { - return new Stop(); - } else { - let it = $[0]; - let next_iterator = $[1]; - return do_append( - it.continuation, - () => { return do_flatten(next_iterator); }, - ); - } -} - -export function flatten(iterator) { - let _pipe = () => { return do_flatten(iterator.continuation); }; - return new Iterator(_pipe); -} - -export function concat(iterators) { - return flatten(from_list(iterators)); -} - -export function flat_map(iterator, f) { - let _pipe = iterator; - let _pipe$1 = map(_pipe, f); - return flatten(_pipe$1); -} - -function do_filter(loop$continuation, loop$predicate) { - while (true) { - let continuation = loop$continuation; - let predicate = loop$predicate; - let $ = continuation(); - if ($ instanceof Stop) { - return new Stop(); - } else { - let e = $[0]; - let iterator = $[1]; - let $1 = predicate(e); - if ($1) { - return new Continue(e, () => { return do_filter(iterator, predicate); }); - } else { - loop$continuation = iterator; - loop$predicate = predicate; - } - } - } -} - -export function filter(iterator, predicate) { - let _pipe = () => { return do_filter(iterator.continuation, predicate); }; - return new Iterator(_pipe); -} - -function do_filter_map(loop$continuation, loop$f) { - while (true) { - let continuation = loop$continuation; - let f = loop$f; - let $ = continuation(); - if ($ instanceof Stop) { - return new Stop(); - } else { - let e = $[0]; - let next = $[1]; - let $1 = f(e); - if ($1.isOk()) { - let e$1 = $1[0]; - return new Continue(e$1, () => { return do_filter_map(next, f); }); - } else { - loop$continuation = next; - loop$f = f; - } - } - } -} - -export function filter_map(iterator, f) { - let _pipe = () => { return do_filter_map(iterator.continuation, f); }; - return new Iterator(_pipe); -} - -export function cycle(iterator) { - let _pipe = repeat(iterator); - return flatten(_pipe); -} - -function do_find(loop$continuation, loop$f) { - while (true) { - let continuation = loop$continuation; - let f = loop$f; - let $ = continuation(); - if ($ instanceof Stop) { - return new Error(undefined); - } else { - let e = $[0]; - let next = $[1]; - let $1 = f(e); - if ($1) { - return new Ok(e); - } else { - loop$continuation = next; - loop$f = f; - } - } - } -} - -export function find(haystack, is_desired) { - let _pipe = haystack.continuation; - return do_find(_pipe, is_desired); -} - -function do_find_map(loop$continuation, loop$f) { - while (true) { - let continuation = loop$continuation; - let f = loop$f; - let $ = continuation(); - if ($ instanceof Stop) { - return new Error(undefined); - } else { - let e = $[0]; - let next = $[1]; - let $1 = f(e); - if ($1.isOk()) { - let e$1 = $1[0]; - return new Ok(e$1); - } else { - loop$continuation = next; - loop$f = f; - } - } - } -} - -export function find_map(haystack, is_desired) { - let _pipe = haystack.continuation; - return do_find_map(_pipe, is_desired); -} - -function do_index(continuation, next) { - return () => { - let $ = continuation(); - if ($ instanceof Stop) { - return new Stop(); - } else { - let e = $[0]; - let continuation$1 = $[1]; - return new Continue([e, next], do_index(continuation$1, next + 1)); - } - }; -} - -export function index(iterator) { - let _pipe = iterator.continuation; - let _pipe$1 = do_index(_pipe, 0); - return new Iterator(_pipe$1); -} - -export function iterate(initial, f) { - return unfold(initial, (element) => { return new Next(element, f(element)); }); -} - -function do_take_while(continuation, predicate) { - return () => { - let $ = continuation(); - if ($ instanceof Stop) { - return new Stop(); - } else { - let e = $[0]; - let next = $[1]; - let $1 = predicate(e); - if (!$1) { - return new Stop(); - } else { - return new Continue(e, do_take_while(next, predicate)); - } - } - }; -} - -export function take_while(iterator, predicate) { - let _pipe = iterator.continuation; - let _pipe$1 = do_take_while(_pipe, predicate); - return new Iterator(_pipe$1); -} - -function do_drop_while(loop$continuation, loop$predicate) { - while (true) { - let continuation = loop$continuation; - let predicate = loop$predicate; - let $ = continuation(); - if ($ instanceof Stop) { - return new Stop(); - } else { - let e = $[0]; - let next = $[1]; - let $1 = predicate(e); - if (!$1) { - return new Continue(e, next); - } else { - loop$continuation = next; - loop$predicate = predicate; - } - } - } -} - -export function drop_while(iterator, predicate) { - let _pipe = () => { return do_drop_while(iterator.continuation, predicate); }; - return new Iterator(_pipe); -} - -function do_scan(continuation, f, accumulator) { - return () => { - let $ = continuation(); - if ($ instanceof Stop) { - return new Stop(); - } else { - let el = $[0]; - let next = $[1]; - let accumulated = f(accumulator, el); - return new Continue(accumulated, do_scan(next, f, accumulated)); - } - }; -} - -export function scan(iterator, initial, f) { - let _pipe = iterator.continuation; - let _pipe$1 = do_scan(_pipe, f, initial); - return new Iterator(_pipe$1); -} - -function do_zip(left, right) { - return () => { - let $ = left(); - if ($ instanceof Stop) { - return new Stop(); - } else { - let el_left = $[0]; - let next_left = $[1]; - let $1 = right(); - if ($1 instanceof Stop) { - return new Stop(); - } else { - let el_right = $1[0]; - let next_right = $1[1]; - return new Continue([el_left, el_right], do_zip(next_left, next_right)); - } - } - }; -} - -export function zip(left, right) { - let _pipe = do_zip(left.continuation, right.continuation); - return new Iterator(_pipe); -} - -function next_chunk( - loop$continuation, - loop$f, - loop$previous_key, - loop$current_chunk -) { - while (true) { - let continuation = loop$continuation; - let f = loop$f; - let previous_key = loop$previous_key; - let current_chunk = loop$current_chunk; - let $ = continuation(); - if ($ instanceof Stop) { - return new LastBy($list.reverse(current_chunk)); - } else { - let e = $[0]; - let next = $[1]; - let key = f(e); - let $1 = isEqual(key, previous_key); - if ($1) { - loop$continuation = next; - loop$f = f; - loop$previous_key = key; - loop$current_chunk = listPrepend(e, current_chunk); - } else { - return new AnotherBy($list.reverse(current_chunk), key, e, next); - } - } - } -} - -function do_chunk(continuation, f, previous_key, previous_element) { - let $ = next_chunk(continuation, f, previous_key, toList([previous_element])); - if ($ instanceof LastBy) { - let chunk$1 = $[0]; - return new Continue(chunk$1, stop); - } else { - let chunk$1 = $[0]; - let key = $[1]; - let el = $[2]; - let next = $[3]; - return new Continue(chunk$1, () => { return do_chunk(next, f, key, el); }); - } -} - -export function chunk(iterator, f) { - let _pipe = () => { - let $ = iterator.continuation(); - if ($ instanceof Stop) { - return new Stop(); - } else { - let e = $[0]; - let next = $[1]; - return do_chunk(next, f, f(e), e); - } - }; - return new Iterator(_pipe); -} - -function next_sized_chunk(loop$continuation, loop$left, loop$current_chunk) { - while (true) { - let continuation = loop$continuation; - let left = loop$left; - let current_chunk = loop$current_chunk; - let $ = continuation(); - if ($ instanceof Stop) { - if (current_chunk.hasLength(0)) { - return new NoMore(); - } else { - let remaining = current_chunk; - return new Last($list.reverse(remaining)); - } - } else { - let e = $[0]; - let next = $[1]; - let chunk$1 = listPrepend(e, current_chunk); - let $1 = left > 1; - if (!$1) { - return new Another($list.reverse(chunk$1), next); - } else { - loop$continuation = next; - loop$left = left - 1; - loop$current_chunk = chunk$1; - } - } - } -} - -function do_sized_chunk(continuation, count) { - return () => { - let $ = next_sized_chunk(continuation, count, toList([])); - if ($ instanceof NoMore) { - return new Stop(); - } else if ($ instanceof Last) { - let chunk$1 = $[0]; - return new Continue(chunk$1, stop); - } else { - let chunk$1 = $[0]; - let next_element = $[1]; - return new Continue(chunk$1, do_sized_chunk(next_element, count)); - } - }; -} - -export function sized_chunk(iterator, count) { - let _pipe = iterator.continuation; - let _pipe$1 = do_sized_chunk(_pipe, count); - return new Iterator(_pipe$1); -} - -function do_intersperse(continuation, separator) { - let $ = continuation(); - if ($ instanceof Stop) { - return new Stop(); - } else { - let e = $[0]; - let next = $[1]; - let next_interspersed = () => { return do_intersperse(next, separator); }; - return new Continue( - separator, - () => { return new Continue(e, next_interspersed); }, - ); - } -} - -export function intersperse(iterator, elem) { - let _pipe = () => { - let $ = iterator.continuation(); - if ($ instanceof Stop) { - return new Stop(); - } else { - let e = $[0]; - let next = $[1]; - return new Continue(e, () => { return do_intersperse(next, elem); }); - } - }; - return new Iterator(_pipe); -} - -function do_any(loop$continuation, loop$predicate) { - while (true) { - let continuation = loop$continuation; - let predicate = loop$predicate; - let $ = continuation(); - if ($ instanceof Stop) { - return false; - } else { - let e = $[0]; - let next = $[1]; - let $1 = predicate(e); - if ($1) { - return true; - } else { - loop$continuation = next; - loop$predicate = predicate; - } - } - } -} - -export function any(iterator, predicate) { - let _pipe = iterator.continuation; - return do_any(_pipe, predicate); -} - -function do_all(loop$continuation, loop$predicate) { - while (true) { - let continuation = loop$continuation; - let predicate = loop$predicate; - let $ = continuation(); - if ($ instanceof Stop) { - return true; - } else { - let e = $[0]; - let next = $[1]; - let $1 = predicate(e); - if ($1) { - loop$continuation = next; - loop$predicate = predicate; - } else { - return false; - } - } - } -} - -export function all(iterator, predicate) { - let _pipe = iterator.continuation; - return do_all(_pipe, predicate); -} - -function update_group_with(el) { - return (maybe_group) => { - if (maybe_group instanceof Some) { - let group$1 = maybe_group[0]; - return listPrepend(el, group$1); - } else { - return toList([el]); - } - }; -} - -function group_updater(f) { - return (groups, elem) => { - let _pipe = groups; - return $dict.upsert(_pipe, f(elem), update_group_with(elem)); - }; -} - -export function group(iterator, key) { - let _pipe = iterator; - let _pipe$1 = fold(_pipe, $dict.new$(), group_updater(key)); - return $dict.map_values( - _pipe$1, - (_, group) => { return $list.reverse(group); }, - ); -} - -export function reduce(iterator, f) { - let $ = iterator.continuation(); - if ($ instanceof Stop) { - return new Error(undefined); - } else { - let e = $[0]; - let next = $[1]; - let _pipe = do_fold(next, f, e); - return new Ok(_pipe); - } -} - -export function last(iterator) { - let _pipe = iterator; - return reduce(_pipe, (_, elem) => { return elem; }); -} - -export function empty() { - return new Iterator(stop); -} - -export function once(f) { - let _pipe = () => { return new Continue(f(), stop); }; - return new Iterator(_pipe); -} - -export function range(start, stop) { - let $ = $int.compare(start, stop); - if ($ instanceof $order.Eq) { - return once(() => { return start; }); - } else if ($ instanceof $order.Gt) { - return unfold( - start, - (current) => { - let $1 = current < stop; - if (!$1) { - return new Next(current, current - 1); - } else { - return new Done(); - } - }, - ); - } else { - return unfold( - start, - (current) => { - let $1 = current > stop; - if (!$1) { - return new Next(current, current + 1); - } else { - return new Done(); - } - }, - ); - } -} - -export function single(elem) { - return once(() => { return elem; }); -} - -function do_interleave(current, next) { - let $ = current(); - if ($ instanceof Stop) { - return next(); - } else { - let e = $[0]; - let next_other = $[1]; - return new Continue(e, () => { return do_interleave(next, next_other); }); - } -} - -export function interleave(left, right) { - let _pipe = () => { - return do_interleave(left.continuation, right.continuation); - }; - return new Iterator(_pipe); -} - -function do_fold_until(loop$continuation, loop$f, loop$accumulator) { - while (true) { - let continuation = loop$continuation; - let f = loop$f; - let accumulator = loop$accumulator; - let $ = continuation(); - if ($ instanceof Stop) { - return accumulator; - } else { - let elem = $[0]; - let next = $[1]; - let $1 = f(accumulator, elem); - if ($1 instanceof $list.Continue) { - let accumulator$1 = $1[0]; - loop$continuation = next; - loop$f = f; - loop$accumulator = accumulator$1; - } else { - let accumulator$1 = $1[0]; - return accumulator$1; - } - } - } -} - -export function fold_until(iterator, initial, f) { - let _pipe = iterator.continuation; - return do_fold_until(_pipe, f, initial); -} - -function do_try_fold(loop$continuation, loop$f, loop$accumulator) { - while (true) { - let continuation = loop$continuation; - let f = loop$f; - let accumulator = loop$accumulator; - let $ = continuation(); - if ($ instanceof Stop) { - return new Ok(accumulator); - } else { - let elem = $[0]; - let next = $[1]; - let $1 = f(accumulator, elem); - if ($1.isOk()) { - let result = $1[0]; - loop$continuation = next; - loop$f = f; - loop$accumulator = result; - } else { - let error = $1; - return error; - } - } - } -} - -export function try_fold(iterator, initial, f) { - let _pipe = iterator.continuation; - return do_try_fold(_pipe, f, initial); -} - -export function first(iterator) { - let $ = iterator.continuation(); - if ($ instanceof Stop) { - return new Error(undefined); - } else { - let e = $[0]; - return new Ok(e); - } -} - -export function at(iterator, index) { - let _pipe = iterator; - let _pipe$1 = drop(_pipe, index); - return first(_pipe$1); -} - -function do_length(loop$continuation, loop$length) { - while (true) { - let continuation = loop$continuation; - let length = loop$length; - let $ = continuation(); - if ($ instanceof Stop) { - return length; - } else { - let next = $[1]; - loop$continuation = next; - loop$length = length + 1; - } - } -} - -export function length(iterator) { - let _pipe = iterator.continuation; - return do_length(_pipe, 0); -} - -export function each(iterator, f) { - let _pipe = iterator; - let _pipe$1 = map(_pipe, f); - return run(_pipe$1); -} - -export function yield$(element, next) { - return new Iterator( - () => { - return new Continue(element, () => { return next().continuation(); }); - }, - ); -} diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/list.mjs b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/list.mjs deleted file mode 100644 index a7adb2421ea..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/list.mjs +++ /dev/null @@ -1,1680 +0,0 @@ -import { - Ok, - Error, - toList, - prepend as listPrepend, - CustomType as $CustomType, - isEqual, -} from "../gleam.mjs"; -import * as $dict from "../gleam/dict.mjs"; -import * as $float from "../gleam/float.mjs"; -import * as $int from "../gleam/int.mjs"; -import * as $order from "../gleam/order.mjs"; -import * as $pair from "../gleam/pair.mjs"; - -export class Continue extends $CustomType { - constructor(x0) { - super(); - this[0] = x0; - } -} - -export class Stop extends $CustomType { - constructor(x0) { - super(); - this[0] = x0; - } -} - -class Ascending extends $CustomType {} - -class Descending extends $CustomType {} - -function count_length(loop$list, loop$count) { - while (true) { - let list = loop$list; - let count = loop$count; - if (list.atLeastLength(1)) { - let list$1 = list.tail; - loop$list = list$1; - loop$count = count + 1; - } else { - return count; - } - } -} - -export function length(list) { - return count_length(list, 0); -} - -function do_reverse(loop$remaining, loop$accumulator) { - while (true) { - let remaining = loop$remaining; - let accumulator = loop$accumulator; - if (remaining.hasLength(0)) { - return accumulator; - } else { - let item = remaining.head; - let rest$1 = remaining.tail; - loop$remaining = rest$1; - loop$accumulator = listPrepend(item, accumulator); - } - } -} - -export function reverse(list) { - return do_reverse(list, toList([])); -} - -export function is_empty(list) { - return isEqual(list, toList([])); -} - -export function contains(loop$list, loop$elem) { - while (true) { - let list = loop$list; - let elem = loop$elem; - if (list.hasLength(0)) { - return false; - } else if (list.atLeastLength(1) && (isEqual(list.head, elem))) { - let first$1 = list.head; - return true; - } else { - let rest$1 = list.tail; - loop$list = rest$1; - loop$elem = elem; - } - } -} - -export function first(list) { - if (list.hasLength(0)) { - return new Error(undefined); - } else { - let x = list.head; - return new Ok(x); - } -} - -export function rest(list) { - if (list.hasLength(0)) { - return new Error(undefined); - } else { - let rest$1 = list.tail; - return new Ok(rest$1); - } -} - -function update_group(f) { - return (groups, elem) => { - let $ = $dict.get(groups, f(elem)); - if ($.isOk()) { - let existing = $[0]; - return $dict.insert(groups, f(elem), listPrepend(elem, existing)); - } else { - return $dict.insert(groups, f(elem), toList([elem])); - } - }; -} - -function do_filter(loop$list, loop$fun, loop$acc) { - while (true) { - let list = loop$list; - let fun = loop$fun; - let acc = loop$acc; - if (list.hasLength(0)) { - return reverse(acc); - } else { - let first$1 = list.head; - let rest$1 = list.tail; - let new_acc = (() => { - let $ = fun(first$1); - if ($) { - return listPrepend(first$1, acc); - } else { - return acc; - } - })(); - loop$list = rest$1; - loop$fun = fun; - loop$acc = new_acc; - } - } -} - -export function filter(list, predicate) { - return do_filter(list, predicate, toList([])); -} - -function do_filter_map(loop$list, loop$fun, loop$acc) { - while (true) { - let list = loop$list; - let fun = loop$fun; - let acc = loop$acc; - if (list.hasLength(0)) { - return reverse(acc); - } else { - let first$1 = list.head; - let rest$1 = list.tail; - let new_acc = (() => { - let $ = fun(first$1); - if ($.isOk()) { - let first$2 = $[0]; - return listPrepend(first$2, acc); - } else { - return acc; - } - })(); - loop$list = rest$1; - loop$fun = fun; - loop$acc = new_acc; - } - } -} - -export function filter_map(list, fun) { - return do_filter_map(list, fun, toList([])); -} - -function do_map(loop$list, loop$fun, loop$acc) { - while (true) { - let list = loop$list; - let fun = loop$fun; - let acc = loop$acc; - if (list.hasLength(0)) { - return reverse(acc); - } else { - let first$1 = list.head; - let rest$1 = list.tail; - loop$list = rest$1; - loop$fun = fun; - loop$acc = listPrepend(fun(first$1), acc); - } - } -} - -export function map(list, fun) { - return do_map(list, fun, toList([])); -} - -function do_map2(loop$list1, loop$list2, loop$fun, loop$acc) { - while (true) { - let list1 = loop$list1; - let list2 = loop$list2; - let fun = loop$fun; - let acc = loop$acc; - if (list1.hasLength(0)) { - return reverse(acc); - } else if (list2.hasLength(0)) { - return reverse(acc); - } else { - let a = list1.head; - let as_ = list1.tail; - let b = list2.head; - let bs = list2.tail; - loop$list1 = as_; - loop$list2 = bs; - loop$fun = fun; - loop$acc = listPrepend(fun(a, b), acc); - } - } -} - -export function map2(list1, list2, fun) { - return do_map2(list1, list2, fun, toList([])); -} - -function do_index_map(loop$list, loop$fun, loop$index, loop$acc) { - while (true) { - let list = loop$list; - let fun = loop$fun; - let index = loop$index; - let acc = loop$acc; - if (list.hasLength(0)) { - return reverse(acc); - } else { - let first$1 = list.head; - let rest$1 = list.tail; - let acc$1 = listPrepend(fun(first$1, index), acc); - loop$list = rest$1; - loop$fun = fun; - loop$index = index + 1; - loop$acc = acc$1; - } - } -} - -export function index_map(list, fun) { - return do_index_map(list, fun, 0, toList([])); -} - -function do_try_map(loop$list, loop$fun, loop$acc) { - while (true) { - let list = loop$list; - let fun = loop$fun; - let acc = loop$acc; - if (list.hasLength(0)) { - return new Ok(reverse(acc)); - } else { - let first$1 = list.head; - let rest$1 = list.tail; - let $ = fun(first$1); - if ($.isOk()) { - let first$2 = $[0]; - loop$list = rest$1; - loop$fun = fun; - loop$acc = listPrepend(first$2, acc); - } else { - let error = $[0]; - return new Error(error); - } - } - } -} - -export function try_map(list, fun) { - return do_try_map(list, fun, toList([])); -} - -export function drop(loop$list, loop$n) { - while (true) { - let list = loop$list; - let n = loop$n; - let $ = n <= 0; - if ($) { - return list; - } else { - if (list.hasLength(0)) { - return toList([]); - } else { - let rest$1 = list.tail; - loop$list = rest$1; - loop$n = n - 1; - } - } - } -} - -function do_take(loop$list, loop$n, loop$acc) { - while (true) { - let list = loop$list; - let n = loop$n; - let acc = loop$acc; - let $ = n <= 0; - if ($) { - return reverse(acc); - } else { - if (list.hasLength(0)) { - return reverse(acc); - } else { - let first$1 = list.head; - let rest$1 = list.tail; - loop$list = rest$1; - loop$n = n - 1; - loop$acc = listPrepend(first$1, acc); - } - } - } -} - -export function take(list, n) { - return do_take(list, n, toList([])); -} - -export function new$() { - return toList([]); -} - -export function wrap(item) { - return toList([item]); -} - -function do_append(loop$first, loop$second) { - while (true) { - let first = loop$first; - let second = loop$second; - if (first.hasLength(0)) { - return second; - } else { - let item = first.head; - let rest$1 = first.tail; - loop$first = rest$1; - loop$second = listPrepend(item, second); - } - } -} - -export function append(first, second) { - return do_append(reverse(first), second); -} - -export function prepend(list, item) { - return listPrepend(item, list); -} - -function reverse_and_prepend(loop$prefix, loop$suffix) { - while (true) { - let prefix = loop$prefix; - let suffix = loop$suffix; - if (prefix.hasLength(0)) { - return suffix; - } else { - let first$1 = prefix.head; - let rest$1 = prefix.tail; - loop$prefix = rest$1; - loop$suffix = listPrepend(first$1, suffix); - } - } -} - -function do_concat(loop$lists, loop$acc) { - while (true) { - let lists = loop$lists; - let acc = loop$acc; - if (lists.hasLength(0)) { - return reverse(acc); - } else { - let list = lists.head; - let further_lists = lists.tail; - loop$lists = further_lists; - loop$acc = reverse_and_prepend(list, acc); - } - } -} - -export function concat(lists) { - return do_concat(lists, toList([])); -} - -export function flatten(lists) { - return do_concat(lists, toList([])); -} - -export function flat_map(list, fun) { - let _pipe = map(list, fun); - return flatten(_pipe); -} - -export function fold(loop$list, loop$initial, loop$fun) { - while (true) { - let list = loop$list; - let initial = loop$initial; - let fun = loop$fun; - if (list.hasLength(0)) { - return initial; - } else { - let x = list.head; - let rest$1 = list.tail; - loop$list = rest$1; - loop$initial = fun(initial, x); - loop$fun = fun; - } - } -} - -export function count(list, predicate) { - return fold( - list, - 0, - (acc, value) => { - let $ = predicate(value); - if ($) { - return acc + 1; - } else { - return acc; - } - }, - ); -} - -export function group(list, key) { - return fold(list, $dict.new$(), update_group(key)); -} - -export function map_fold(list, initial, fun) { - let _pipe = fold( - list, - [initial, toList([])], - (acc, item) => { - let current_acc = acc[0]; - let items = acc[1]; - let $ = fun(current_acc, item); - let next_acc = $[0]; - let next_item = $[1]; - return [next_acc, listPrepend(next_item, items)]; - }, - ); - return $pair.map_second(_pipe, reverse); -} - -export function fold_right(list, initial, fun) { - if (list.hasLength(0)) { - return initial; - } else { - let x = list.head; - let rest$1 = list.tail; - return fun(fold_right(rest$1, initial, fun), x); - } -} - -function do_index_fold(loop$over, loop$acc, loop$with, loop$index) { - while (true) { - let over = loop$over; - let acc = loop$acc; - let with$ = loop$with; - let index = loop$index; - if (over.hasLength(0)) { - return acc; - } else { - let first$1 = over.head; - let rest$1 = over.tail; - loop$over = rest$1; - loop$acc = with$(acc, first$1, index); - loop$with = with$; - loop$index = index + 1; - } - } -} - -export function index_fold(list, initial, fun) { - return do_index_fold(list, initial, fun, 0); -} - -export function try_fold(loop$list, loop$initial, loop$fun) { - while (true) { - let list = loop$list; - let initial = loop$initial; - let fun = loop$fun; - if (list.hasLength(0)) { - return new Ok(initial); - } else { - let first$1 = list.head; - let rest$1 = list.tail; - let $ = fun(initial, first$1); - if ($.isOk()) { - let result = $[0]; - loop$list = rest$1; - loop$initial = result; - loop$fun = fun; - } else { - let error = $; - return error; - } - } - } -} - -export function fold_until(loop$list, loop$initial, loop$fun) { - while (true) { - let list = loop$list; - let initial = loop$initial; - let fun = loop$fun; - if (list.hasLength(0)) { - return initial; - } else { - let first$1 = list.head; - let rest$1 = list.tail; - let $ = fun(initial, first$1); - if ($ instanceof Continue) { - let next_accumulator = $[0]; - loop$list = rest$1; - loop$initial = next_accumulator; - loop$fun = fun; - } else { - let b = $[0]; - return b; - } - } - } -} - -export function find(loop$list, loop$is_desired) { - while (true) { - let list = loop$list; - let is_desired = loop$is_desired; - if (list.hasLength(0)) { - return new Error(undefined); - } else { - let x = list.head; - let rest$1 = list.tail; - let $ = is_desired(x); - if ($) { - return new Ok(x); - } else { - loop$list = rest$1; - loop$is_desired = is_desired; - } - } - } -} - -export function find_map(loop$list, loop$fun) { - while (true) { - let list = loop$list; - let fun = loop$fun; - if (list.hasLength(0)) { - return new Error(undefined); - } else { - let x = list.head; - let rest$1 = list.tail; - let $ = fun(x); - if ($.isOk()) { - let x$1 = $[0]; - return new Ok(x$1); - } else { - loop$list = rest$1; - loop$fun = fun; - } - } - } -} - -export function all(loop$list, loop$predicate) { - while (true) { - let list = loop$list; - let predicate = loop$predicate; - if (list.hasLength(0)) { - return true; - } else { - let first$1 = list.head; - let rest$1 = list.tail; - let $ = predicate(first$1); - if ($) { - loop$list = rest$1; - loop$predicate = predicate; - } else { - return false; - } - } - } -} - -export function any(loop$list, loop$predicate) { - while (true) { - let list = loop$list; - let predicate = loop$predicate; - if (list.hasLength(0)) { - return false; - } else { - let first$1 = list.head; - let rest$1 = list.tail; - let $ = predicate(first$1); - if ($) { - return true; - } else { - loop$list = rest$1; - loop$predicate = predicate; - } - } - } -} - -function do_zip(loop$one, loop$other, loop$acc) { - while (true) { - let one = loop$one; - let other = loop$other; - let acc = loop$acc; - if (one.atLeastLength(1) && other.atLeastLength(1)) { - let first_one = one.head; - let rest_one = one.tail; - let first_other = other.head; - let rest_other = other.tail; - loop$one = rest_one; - loop$other = rest_other; - loop$acc = listPrepend([first_one, first_other], acc); - } else { - return reverse(acc); - } - } -} - -export function zip(list, other) { - return do_zip(list, other, toList([])); -} - -export function strict_zip(list, other) { - let $ = length(list) === length(other); - if ($) { - return new Ok(zip(list, other)); - } else { - return new Error(undefined); - } -} - -function do_unzip(loop$input, loop$one, loop$other) { - while (true) { - let input = loop$input; - let one = loop$one; - let other = loop$other; - if (input.hasLength(0)) { - return [reverse(one), reverse(other)]; - } else { - let first_one = input.head[0]; - let first_other = input.head[1]; - let rest$1 = input.tail; - loop$input = rest$1; - loop$one = listPrepend(first_one, one); - loop$other = listPrepend(first_other, other); - } - } -} - -export function unzip(input) { - return do_unzip(input, toList([]), toList([])); -} - -function do_intersperse(loop$list, loop$separator, loop$acc) { - while (true) { - let list = loop$list; - let separator = loop$separator; - let acc = loop$acc; - if (list.hasLength(0)) { - return reverse(acc); - } else { - let x = list.head; - let rest$1 = list.tail; - loop$list = rest$1; - loop$separator = separator; - loop$acc = listPrepend(x, listPrepend(separator, acc)); - } - } -} - -export function intersperse(list, elem) { - if (list.hasLength(0)) { - return list; - } else if (list.hasLength(1)) { - return list; - } else { - let x = list.head; - let rest$1 = list.tail; - return do_intersperse(rest$1, elem, toList([x])); - } -} - -export function unique(list) { - if (list.hasLength(0)) { - return toList([]); - } else { - let x = list.head; - let rest$1 = list.tail; - return listPrepend( - x, - unique(filter(rest$1, (y) => { return !isEqual(y, x); })), - ); - } -} - -function sequences( - loop$list, - loop$compare, - loop$growing, - loop$direction, - loop$prev, - loop$acc -) { - while (true) { - let list = loop$list; - let compare = loop$compare; - let growing = loop$growing; - let direction = loop$direction; - let prev = loop$prev; - let acc = loop$acc; - let growing$1 = listPrepend(prev, growing); - if (list.hasLength(0)) { - if (direction instanceof Ascending) { - return listPrepend(do_reverse(growing$1, toList([])), acc); - } else { - return listPrepend(growing$1, acc); - } - } else { - let new$1 = list.head; - let rest$1 = list.tail; - let $ = compare(prev, new$1); - if ($ instanceof $order.Gt && direction instanceof Descending) { - loop$list = rest$1; - loop$compare = compare; - loop$growing = growing$1; - loop$direction = direction; - loop$prev = new$1; - loop$acc = acc; - } else if ($ instanceof $order.Lt && direction instanceof Ascending) { - loop$list = rest$1; - loop$compare = compare; - loop$growing = growing$1; - loop$direction = direction; - loop$prev = new$1; - loop$acc = acc; - } else if ($ instanceof $order.Eq && direction instanceof Ascending) { - loop$list = rest$1; - loop$compare = compare; - loop$growing = growing$1; - loop$direction = direction; - loop$prev = new$1; - loop$acc = acc; - } else if ($ instanceof $order.Gt && direction instanceof Ascending) { - let acc$1 = (() => { - if (direction instanceof Ascending) { - return listPrepend(do_reverse(growing$1, toList([])), acc); - } else { - return listPrepend(growing$1, acc); - } - })(); - if (rest$1.hasLength(0)) { - return listPrepend(toList([new$1]), acc$1); - } else { - let next = rest$1.head; - let rest$2 = rest$1.tail; - let direction$1 = (() => { - let $1 = compare(new$1, next); - if ($1 instanceof $order.Lt) { - return new Ascending(); - } else if ($1 instanceof $order.Eq) { - return new Ascending(); - } else { - return new Descending(); - } - })(); - loop$list = rest$2; - loop$compare = compare; - loop$growing = toList([new$1]); - loop$direction = direction$1; - loop$prev = next; - loop$acc = acc$1; - } - } else if ($ instanceof $order.Lt && direction instanceof Descending) { - let acc$1 = (() => { - if (direction instanceof Ascending) { - return listPrepend(do_reverse(growing$1, toList([])), acc); - } else { - return listPrepend(growing$1, acc); - } - })(); - if (rest$1.hasLength(0)) { - return listPrepend(toList([new$1]), acc$1); - } else { - let next = rest$1.head; - let rest$2 = rest$1.tail; - let direction$1 = (() => { - let $1 = compare(new$1, next); - if ($1 instanceof $order.Lt) { - return new Ascending(); - } else if ($1 instanceof $order.Eq) { - return new Ascending(); - } else { - return new Descending(); - } - })(); - loop$list = rest$2; - loop$compare = compare; - loop$growing = toList([new$1]); - loop$direction = direction$1; - loop$prev = next; - loop$acc = acc$1; - } - } else { - let acc$1 = (() => { - if (direction instanceof Ascending) { - return listPrepend(do_reverse(growing$1, toList([])), acc); - } else { - return listPrepend(growing$1, acc); - } - })(); - if (rest$1.hasLength(0)) { - return listPrepend(toList([new$1]), acc$1); - } else { - let next = rest$1.head; - let rest$2 = rest$1.tail; - let direction$1 = (() => { - let $1 = compare(new$1, next); - if ($1 instanceof $order.Lt) { - return new Ascending(); - } else if ($1 instanceof $order.Eq) { - return new Ascending(); - } else { - return new Descending(); - } - })(); - loop$list = rest$2; - loop$compare = compare; - loop$growing = toList([new$1]); - loop$direction = direction$1; - loop$prev = next; - loop$acc = acc$1; - } - } - } - } -} - -function merge_ascendings(loop$list1, loop$list2, loop$compare, loop$acc) { - while (true) { - let list1 = loop$list1; - let list2 = loop$list2; - let compare = loop$compare; - let acc = loop$acc; - if (list1.hasLength(0)) { - let list = list2; - return do_reverse(list, acc); - } else if (list2.hasLength(0)) { - let list = list1; - return do_reverse(list, acc); - } else { - let first1 = list1.head; - let rest1 = list1.tail; - let first2 = list2.head; - let rest2 = list2.tail; - let $ = compare(first1, first2); - if ($ instanceof $order.Lt) { - loop$list1 = rest1; - loop$list2 = list2; - loop$compare = compare; - loop$acc = listPrepend(first1, acc); - } else if ($ instanceof $order.Gt) { - loop$list1 = list1; - loop$list2 = rest2; - loop$compare = compare; - loop$acc = listPrepend(first2, acc); - } else { - loop$list1 = list1; - loop$list2 = rest2; - loop$compare = compare; - loop$acc = listPrepend(first2, acc); - } - } - } -} - -function merge_ascending_pairs(loop$sequences, loop$compare, loop$acc) { - while (true) { - let sequences = loop$sequences; - let compare = loop$compare; - let acc = loop$acc; - if (sequences.hasLength(0)) { - return do_reverse(acc, toList([])); - } else if (sequences.hasLength(1)) { - let sequence = sequences.head; - return do_reverse( - listPrepend(do_reverse(sequence, toList([])), acc), - toList([]), - ); - } else { - let ascending1 = sequences.head; - let ascending2 = sequences.tail.head; - let rest$1 = sequences.tail.tail; - let descending = merge_ascendings( - ascending1, - ascending2, - compare, - toList([]), - ); - loop$sequences = rest$1; - loop$compare = compare; - loop$acc = listPrepend(descending, acc); - } - } -} - -function merge_descendings(loop$list1, loop$list2, loop$compare, loop$acc) { - while (true) { - let list1 = loop$list1; - let list2 = loop$list2; - let compare = loop$compare; - let acc = loop$acc; - if (list1.hasLength(0)) { - let list = list2; - return do_reverse(list, acc); - } else if (list2.hasLength(0)) { - let list = list1; - return do_reverse(list, acc); - } else { - let first1 = list1.head; - let rest1 = list1.tail; - let first2 = list2.head; - let rest2 = list2.tail; - let $ = compare(first1, first2); - if ($ instanceof $order.Lt) { - loop$list1 = list1; - loop$list2 = rest2; - loop$compare = compare; - loop$acc = listPrepend(first2, acc); - } else if ($ instanceof $order.Gt) { - loop$list1 = rest1; - loop$list2 = list2; - loop$compare = compare; - loop$acc = listPrepend(first1, acc); - } else { - loop$list1 = rest1; - loop$list2 = list2; - loop$compare = compare; - loop$acc = listPrepend(first1, acc); - } - } - } -} - -function merge_descending_pairs(loop$sequences, loop$compare, loop$acc) { - while (true) { - let sequences = loop$sequences; - let compare = loop$compare; - let acc = loop$acc; - if (sequences.hasLength(0)) { - return do_reverse(acc, toList([])); - } else if (sequences.hasLength(1)) { - let sequence = sequences.head; - return do_reverse( - listPrepend(do_reverse(sequence, toList([])), acc), - toList([]), - ); - } else { - let descending1 = sequences.head; - let descending2 = sequences.tail.head; - let rest$1 = sequences.tail.tail; - let ascending = merge_descendings( - descending1, - descending2, - compare, - toList([]), - ); - loop$sequences = rest$1; - loop$compare = compare; - loop$acc = listPrepend(ascending, acc); - } - } -} - -function merge_all(loop$sequences, loop$direction, loop$compare) { - while (true) { - let sequences = loop$sequences; - let direction = loop$direction; - let compare = loop$compare; - if (sequences.hasLength(0)) { - return toList([]); - } else if (sequences.hasLength(1) && direction instanceof Ascending) { - let sequence = sequences.head; - return sequence; - } else if (sequences.hasLength(1) && direction instanceof Descending) { - let sequence = sequences.head; - return do_reverse(sequence, toList([])); - } else if (direction instanceof Ascending) { - let sequences$1 = merge_ascending_pairs(sequences, compare, toList([])); - loop$sequences = sequences$1; - loop$direction = new Descending(); - loop$compare = compare; - } else { - let sequences$1 = merge_descending_pairs(sequences, compare, toList([])); - loop$sequences = sequences$1; - loop$direction = new Ascending(); - loop$compare = compare; - } - } -} - -export function sort(list, compare) { - if (list.hasLength(0)) { - return toList([]); - } else if (list.hasLength(1)) { - let x = list.head; - return toList([x]); - } else { - let x = list.head; - let y = list.tail.head; - let rest$1 = list.tail.tail; - let direction = (() => { - let $ = compare(x, y); - if ($ instanceof $order.Lt) { - return new Ascending(); - } else if ($ instanceof $order.Eq) { - return new Ascending(); - } else { - return new Descending(); - } - })(); - let sequences$1 = sequences( - rest$1, - compare, - toList([x]), - direction, - y, - toList([]), - ); - return merge_all(sequences$1, new Ascending(), compare); - } -} - -function tail_recursive_range(loop$start, loop$stop, loop$acc) { - while (true) { - let start = loop$start; - let stop = loop$stop; - let acc = loop$acc; - let $ = $int.compare(start, stop); - if ($ instanceof $order.Eq) { - return listPrepend(stop, acc); - } else if ($ instanceof $order.Gt) { - loop$start = start; - loop$stop = stop + 1; - loop$acc = listPrepend(stop, acc); - } else { - loop$start = start; - loop$stop = stop - 1; - loop$acc = listPrepend(stop, acc); - } - } -} - -export function range(start, stop) { - return tail_recursive_range(start, stop, toList([])); -} - -function do_repeat(loop$item, loop$times, loop$acc) { - while (true) { - let item = loop$item; - let times = loop$times; - let acc = loop$acc; - let $ = times <= 0; - if ($) { - return acc; - } else { - loop$item = item; - loop$times = times - 1; - loop$acc = listPrepend(item, acc); - } - } -} - -export function repeat(a, times) { - return do_repeat(a, times, toList([])); -} - -function do_split(loop$list, loop$n, loop$taken) { - while (true) { - let list = loop$list; - let n = loop$n; - let taken = loop$taken; - let $ = n <= 0; - if ($) { - return [reverse(taken), list]; - } else { - if (list.hasLength(0)) { - return [reverse(taken), toList([])]; - } else { - let first$1 = list.head; - let rest$1 = list.tail; - loop$list = rest$1; - loop$n = n - 1; - loop$taken = listPrepend(first$1, taken); - } - } - } -} - -export function split(list, index) { - return do_split(list, index, toList([])); -} - -function do_split_while(loop$list, loop$f, loop$acc) { - while (true) { - let list = loop$list; - let f = loop$f; - let acc = loop$acc; - if (list.hasLength(0)) { - return [reverse(acc), toList([])]; - } else { - let first$1 = list.head; - let rest$1 = list.tail; - let $ = f(first$1); - if (!$) { - return [reverse(acc), list]; - } else { - loop$list = rest$1; - loop$f = f; - loop$acc = listPrepend(first$1, acc); - } - } - } -} - -export function split_while(list, predicate) { - return do_split_while(list, predicate, toList([])); -} - -export function key_find(keyword_list, desired_key) { - return find_map( - keyword_list, - (keyword) => { - let key = keyword[0]; - let value = keyword[1]; - let $ = isEqual(key, desired_key); - if ($) { - return new Ok(value); - } else { - return new Error(undefined); - } - }, - ); -} - -export function key_filter(keyword_list, desired_key) { - return filter_map( - keyword_list, - (keyword) => { - let key = keyword[0]; - let value = keyword[1]; - let $ = isEqual(key, desired_key); - if ($) { - return new Ok(value); - } else { - return new Error(undefined); - } - }, - ); -} - -function do_pop(loop$haystack, loop$predicate, loop$checked) { - while (true) { - let haystack = loop$haystack; - let predicate = loop$predicate; - let checked = loop$checked; - if (haystack.hasLength(0)) { - return new Error(undefined); - } else { - let x = haystack.head; - let rest$1 = haystack.tail; - let $ = predicate(x); - if ($) { - return new Ok([x, append(reverse(checked), rest$1)]); - } else { - loop$haystack = rest$1; - loop$predicate = predicate; - loop$checked = listPrepend(x, checked); - } - } - } -} - -export function pop(list, is_desired) { - return do_pop(list, is_desired, toList([])); -} - -function do_pop_map(loop$list, loop$mapper, loop$checked) { - while (true) { - let list = loop$list; - let mapper = loop$mapper; - let checked = loop$checked; - if (list.hasLength(0)) { - return new Error(undefined); - } else { - let x = list.head; - let rest$1 = list.tail; - let $ = mapper(x); - if ($.isOk()) { - let y = $[0]; - return new Ok([y, append(reverse(checked), rest$1)]); - } else { - loop$list = rest$1; - loop$mapper = mapper; - loop$checked = listPrepend(x, checked); - } - } - } -} - -export function pop_map(haystack, is_desired) { - return do_pop_map(haystack, is_desired, toList([])); -} - -export function key_pop(list, key) { - return pop_map( - list, - (entry) => { - let k = entry[0]; - let v = entry[1]; - if (isEqual(k, key)) { - let k$1 = k; - return new Ok(v); - } else { - return new Error(undefined); - } - }, - ); -} - -export function key_set(list, key, value) { - if (list.hasLength(0)) { - return toList([[key, value]]); - } else if (list.atLeastLength(1) && (isEqual(list.head[0], key))) { - let k = list.head[0]; - let rest$1 = list.tail; - return listPrepend([key, value], rest$1); - } else { - let first$1 = list.head; - let rest$1 = list.tail; - return listPrepend(first$1, key_set(rest$1, key, value)); - } -} - -export function each(loop$list, loop$f) { - while (true) { - let list = loop$list; - let f = loop$f; - if (list.hasLength(0)) { - return undefined; - } else { - let first$1 = list.head; - let rest$1 = list.tail; - f(first$1); - loop$list = rest$1; - loop$f = f; - } - } -} - -export function try_each(loop$list, loop$fun) { - while (true) { - let list = loop$list; - let fun = loop$fun; - if (list.hasLength(0)) { - return new Ok(undefined); - } else { - let first$1 = list.head; - let rest$1 = list.tail; - let $ = fun(first$1); - if ($.isOk()) { - loop$list = rest$1; - loop$fun = fun; - } else { - let e = $[0]; - return new Error(e); - } - } - } -} - -function do_partition(loop$list, loop$categorise, loop$trues, loop$falses) { - while (true) { - let list = loop$list; - let categorise = loop$categorise; - let trues = loop$trues; - let falses = loop$falses; - if (list.hasLength(0)) { - return [reverse(trues), reverse(falses)]; - } else { - let first$1 = list.head; - let rest$1 = list.tail; - let $ = categorise(first$1); - if ($) { - loop$list = rest$1; - loop$categorise = categorise; - loop$trues = listPrepend(first$1, trues); - loop$falses = falses; - } else { - loop$list = rest$1; - loop$categorise = categorise; - loop$trues = trues; - loop$falses = listPrepend(first$1, falses); - } - } - } -} - -export function partition(list, categorise) { - return do_partition(list, categorise, toList([]), toList([])); -} - -export function permutations(list) { - if (list.hasLength(0)) { - return toList([toList([])]); - } else { - let _pipe = index_map( - list, - (i, i_idx) => { - let _pipe = index_fold( - list, - toList([]), - (acc, j, j_idx) => { - let $ = i_idx === j_idx; - if ($) { - return acc; - } else { - return listPrepend(j, acc); - } - }, - ); - let _pipe$1 = reverse(_pipe); - let _pipe$2 = permutations(_pipe$1); - return map( - _pipe$2, - (permutation) => { return listPrepend(i, permutation); }, - ); - }, - ); - return flatten(_pipe); - } -} - -function do_window(loop$acc, loop$list, loop$n) { - while (true) { - let acc = loop$acc; - let list = loop$list; - let n = loop$n; - let window$1 = take(list, n); - let $ = length(window$1) === n; - if ($) { - loop$acc = listPrepend(window$1, acc); - loop$list = drop(list, 1); - loop$n = n; - } else { - return acc; - } - } -} - -export function window(list, n) { - let $ = n <= 0; - if ($) { - return toList([]); - } else { - let _pipe = do_window(toList([]), list, n); - return reverse(_pipe); - } -} - -export function window_by_2(list) { - return zip(list, drop(list, 1)); -} - -export function drop_while(loop$list, loop$predicate) { - while (true) { - let list = loop$list; - let predicate = loop$predicate; - if (list.hasLength(0)) { - return toList([]); - } else { - let first$1 = list.head; - let rest$1 = list.tail; - let $ = predicate(first$1); - if ($) { - loop$list = rest$1; - loop$predicate = predicate; - } else { - return listPrepend(first$1, rest$1); - } - } - } -} - -function do_take_while(loop$list, loop$predicate, loop$acc) { - while (true) { - let list = loop$list; - let predicate = loop$predicate; - let acc = loop$acc; - if (list.hasLength(0)) { - return reverse(acc); - } else { - let first$1 = list.head; - let rest$1 = list.tail; - let $ = predicate(first$1); - if ($) { - loop$list = rest$1; - loop$predicate = predicate; - loop$acc = listPrepend(first$1, acc); - } else { - return reverse(acc); - } - } - } -} - -export function take_while(list, predicate) { - return do_take_while(list, predicate, toList([])); -} - -function do_chunk( - loop$list, - loop$f, - loop$previous_key, - loop$current_chunk, - loop$acc -) { - while (true) { - let list = loop$list; - let f = loop$f; - let previous_key = loop$previous_key; - let current_chunk = loop$current_chunk; - let acc = loop$acc; - if (list.atLeastLength(1)) { - let first$1 = list.head; - let rest$1 = list.tail; - let key = f(first$1); - let $ = isEqual(key, previous_key); - if (!$) { - let new_acc = listPrepend(reverse(current_chunk), acc); - loop$list = rest$1; - loop$f = f; - loop$previous_key = key; - loop$current_chunk = toList([first$1]); - loop$acc = new_acc; - } else { - loop$list = rest$1; - loop$f = f; - loop$previous_key = key; - loop$current_chunk = listPrepend(first$1, current_chunk); - loop$acc = acc; - } - } else { - return reverse(listPrepend(reverse(current_chunk), acc)); - } - } -} - -export function chunk(list, f) { - if (list.hasLength(0)) { - return toList([]); - } else { - let first$1 = list.head; - let rest$1 = list.tail; - return do_chunk(rest$1, f, f(first$1), toList([first$1]), toList([])); - } -} - -function do_sized_chunk( - loop$list, - loop$count, - loop$left, - loop$current_chunk, - loop$acc -) { - while (true) { - let list = loop$list; - let count = loop$count; - let left = loop$left; - let current_chunk = loop$current_chunk; - let acc = loop$acc; - if (list.hasLength(0)) { - if (current_chunk.hasLength(0)) { - return reverse(acc); - } else { - let remaining = current_chunk; - return reverse(listPrepend(reverse(remaining), acc)); - } - } else { - let first$1 = list.head; - let rest$1 = list.tail; - let chunk$1 = listPrepend(first$1, current_chunk); - let $ = left > 1; - if (!$) { - loop$list = rest$1; - loop$count = count; - loop$left = count; - loop$current_chunk = toList([]); - loop$acc = listPrepend(reverse(chunk$1), acc); - } else { - loop$list = rest$1; - loop$count = count; - loop$left = left - 1; - loop$current_chunk = chunk$1; - loop$acc = acc; - } - } - } -} - -export function sized_chunk(list, count) { - return do_sized_chunk(list, count, count, toList([]), toList([])); -} - -export function reduce(list, fun) { - if (list.hasLength(0)) { - return new Error(undefined); - } else { - let first$1 = list.head; - let rest$1 = list.tail; - return new Ok(fold(rest$1, first$1, fun)); - } -} - -function do_scan(loop$list, loop$accumulator, loop$accumulated, loop$fun) { - while (true) { - let list = loop$list; - let accumulator = loop$accumulator; - let accumulated = loop$accumulated; - let fun = loop$fun; - if (list.hasLength(0)) { - return reverse(accumulated); - } else { - let first$1 = list.head; - let rest$1 = list.tail; - let next = fun(accumulator, first$1); - loop$list = rest$1; - loop$accumulator = next; - loop$accumulated = listPrepend(next, accumulated); - loop$fun = fun; - } - } -} - -export function scan(list, initial, fun) { - return do_scan(list, initial, toList([]), fun); -} - -export function last(list) { - let _pipe = list; - return reduce(_pipe, (_, elem) => { return elem; }); -} - -export function combinations(items, n) { - if (n === 0) { - return toList([toList([])]); - } else { - if (items.hasLength(0)) { - return toList([]); - } else { - let first$1 = items.head; - let rest$1 = items.tail; - let first_combinations = (() => { - let _pipe = map( - combinations(rest$1, n - 1), - (com) => { return listPrepend(first$1, com); }, - ); - return reverse(_pipe); - })(); - return fold( - first_combinations, - combinations(rest$1, n), - (acc, c) => { return listPrepend(c, acc); }, - ); - } - } -} - -function do_combination_pairs(items) { - if (items.hasLength(0)) { - return toList([]); - } else { - let first$1 = items.head; - let rest$1 = items.tail; - let first_combinations = map( - rest$1, - (other) => { return [first$1, other]; }, - ); - return listPrepend(first_combinations, do_combination_pairs(rest$1)); - } -} - -export function combination_pairs(items) { - let _pipe = do_combination_pairs(items); - return flatten(_pipe); -} - -export function transpose(loop$list_of_list) { - while (true) { - let list_of_list = loop$list_of_list; - let take_first = (list) => { - if (list.hasLength(0)) { - return toList([]); - } else if (list.hasLength(1)) { - let f = list.head; - return toList([f]); - } else { - let f = list.head; - return toList([f]); - } - }; - if (list_of_list.hasLength(0)) { - return toList([]); - } else if (list_of_list.atLeastLength(1) && list_of_list.head.hasLength(0)) { - let rest$1 = list_of_list.tail; - loop$list_of_list = rest$1; - } else { - let rows = list_of_list; - let firsts = (() => { - let _pipe = rows; - let _pipe$1 = map(_pipe, take_first); - return flatten(_pipe$1); - })(); - let rest$1 = transpose( - map(rows, (_capture) => { return drop(_capture, 1); }), - ); - return listPrepend(firsts, rest$1); - } - } -} - -export function interleave(list) { - let _pipe = transpose(list); - return flatten(_pipe); -} - -function do_shuffle_pair_unwrap(loop$list, loop$acc) { - while (true) { - let list = loop$list; - let acc = loop$acc; - if (list.hasLength(0)) { - return acc; - } else { - let elem_pair = list.head; - let enumerable = list.tail; - loop$list = enumerable; - loop$acc = listPrepend(elem_pair[1], acc); - } - } -} - -function do_shuffle_by_pair_indexes(list_of_pairs) { - return sort( - list_of_pairs, - (a_pair, b_pair) => { return $float.compare(a_pair[0], b_pair[0]); }, - ); -} - -export function shuffle(list) { - let _pipe = list; - let _pipe$1 = fold( - _pipe, - toList([]), - (acc, a) => { return listPrepend([$float.random(), a], acc); }, - ); - let _pipe$2 = do_shuffle_by_pair_indexes(_pipe$1); - return do_shuffle_pair_unwrap(_pipe$2, toList([])); -} diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/option.mjs b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/option.mjs deleted file mode 100644 index db46d8087bf..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/option.mjs +++ /dev/null @@ -1,149 +0,0 @@ -import { - Ok, - Error, - toList, - prepend as listPrepend, - CustomType as $CustomType, - isEqual, -} from "../gleam.mjs"; - -export class Some extends $CustomType { - constructor(x0) { - super(); - this[0] = x0; - } -} - -export class None extends $CustomType {} - -function do_all(list, acc) { - if (list.hasLength(0)) { - return new Some(acc); - } else { - let x = list.head; - let rest = list.tail; - let accumulate = (acc, item) => { - if (acc instanceof Some && item instanceof Some) { - let values$1 = acc[0]; - let value = item[0]; - return new Some(listPrepend(value, values$1)); - } else { - return new None(); - } - }; - return accumulate(do_all(rest, acc), x); - } -} - -export function all(list) { - return do_all(list, toList([])); -} - -export function is_some(option) { - return !isEqual(option, new None()); -} - -export function is_none(option) { - return isEqual(option, new None()); -} - -export function to_result(option, e) { - if (option instanceof Some) { - let a = option[0]; - return new Ok(a); - } else { - return new Error(e); - } -} - -export function from_result(result) { - if (result.isOk()) { - let a = result[0]; - return new Some(a); - } else { - return new None(); - } -} - -export function unwrap(option, default$) { - if (option instanceof Some) { - let x = option[0]; - return x; - } else { - return default$; - } -} - -export function lazy_unwrap(option, default$) { - if (option instanceof Some) { - let x = option[0]; - return x; - } else { - return default$(); - } -} - -export function map(option, fun) { - if (option instanceof Some) { - let x = option[0]; - return new Some(fun(x)); - } else { - return new None(); - } -} - -export function flatten(option) { - if (option instanceof Some) { - let x = option[0]; - return x; - } else { - return new None(); - } -} - -export function then$(option, fun) { - if (option instanceof Some) { - let x = option[0]; - return fun(x); - } else { - return new None(); - } -} - -export function or(first, second) { - if (first instanceof Some) { - return first; - } else { - return second; - } -} - -export function lazy_or(first, second) { - if (first instanceof Some) { - return first; - } else { - return second(); - } -} - -function do_values(list, acc) { - if (list.hasLength(0)) { - return acc; - } else { - let first = list.head; - let rest = list.tail; - let accumulate = (acc, item) => { - if (item instanceof Some) { - let value = item[0]; - return listPrepend(value, acc); - } else { - return acc; - } - }; - return accumulate(do_values(rest, acc), first); - } -} - -export function values(options) { - return do_values(options, toList([])); -} diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/order.mjs b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/order.mjs deleted file mode 100644 index ee6ee9fc9d8..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/order.mjs +++ /dev/null @@ -1,65 +0,0 @@ -import { CustomType as $CustomType, isEqual } from "../gleam.mjs"; - -export class Lt extends $CustomType {} - -export class Eq extends $CustomType {} - -export class Gt extends $CustomType {} - -export function negate(order) { - if (order instanceof Lt) { - return new Gt(); - } else if (order instanceof Eq) { - return new Eq(); - } else { - return new Lt(); - } -} - -export function to_int(order) { - if (order instanceof Lt) { - return -1; - } else if (order instanceof Eq) { - return 0; - } else { - return 1; - } -} - -export function compare(a, b) { - if (isEqual(a, b)) { - let x = a; - let y = b; - return new Eq(); - } else if (a instanceof Lt) { - return new Lt(); - } else if (a instanceof Eq && b instanceof Gt) { - return new Lt(); - } else { - return new Gt(); - } -} - -export function reverse(orderer) { - return (a, b) => { return orderer(b, a); }; -} - -export function break_tie(order, other) { - if (order instanceof Lt) { - return order; - } else if (order instanceof Gt) { - return order; - } else { - return other; - } -} - -export function lazy_break_tie(order, comparison) { - if (order instanceof Lt) { - return order; - } else if (order instanceof Gt) { - return order; - } else { - return comparison(); - } -} diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/pair.mjs b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/pair.mjs deleted file mode 100644 index d15a9d28c2a..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/pair.mjs +++ /dev/null @@ -1,31 +0,0 @@ -export function first(pair) { - let a = pair[0]; - return a; -} - -export function second(pair) { - let a = pair[1]; - return a; -} - -export function swap(pair) { - let a = pair[0]; - let b = pair[1]; - return [b, a]; -} - -export function map_first(pair, fun) { - let a = pair[0]; - let b = pair[1]; - return [fun(a), b]; -} - -export function map_second(pair, fun) { - let a = pair[0]; - let b = pair[1]; - return [a, fun(b)]; -} - -export function new$(first, second) { - return [first, second]; -} diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/queue.mjs b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/queue.mjs deleted file mode 100644 index 480983f5f70..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/queue.mjs +++ /dev/null @@ -1,149 +0,0 @@ -import { - Ok, - Error, - toList, - prepend as listPrepend, - CustomType as $CustomType, - isEqual, -} from "../gleam.mjs"; -import * as $list from "../gleam/list.mjs"; - -class Queue extends $CustomType { - constructor(in$, out) { - super(); - this.in = in$; - this.out = out; - } -} - -export function new$() { - return new Queue(toList([]), toList([])); -} - -export function from_list(list) { - return new Queue(toList([]), list); -} - -export function to_list(queue) { - let _pipe = queue.out; - return $list.append(_pipe, $list.reverse(queue.in)); -} - -export function is_empty(queue) { - return (isEqual(queue.in, toList([]))) && (isEqual(queue.out, toList([]))); -} - -export function length(queue) { - return $list.length(queue.in) + $list.length(queue.out); -} - -export function push_back(queue, item) { - return new Queue(listPrepend(item, queue.in), queue.out); -} - -export function push_front(queue, item) { - return new Queue(queue.in, listPrepend(item, queue.out)); -} - -export function pop_back(loop$queue) { - while (true) { - let queue = loop$queue; - if (queue instanceof Queue && - queue.in.hasLength(0) && - queue.out.hasLength(0)) { - return new Error(undefined); - } else if (queue instanceof Queue && queue.in.hasLength(0)) { - let out = queue.out; - loop$queue = new Queue($list.reverse(out), toList([])); - } else { - let first = queue.in.head; - let rest = queue.in.tail; - let out = queue.out; - let queue$1 = new Queue(rest, out); - return new Ok([first, queue$1]); - } - } -} - -export function pop_front(loop$queue) { - while (true) { - let queue = loop$queue; - if (queue instanceof Queue && - queue.in.hasLength(0) && - queue.out.hasLength(0)) { - return new Error(undefined); - } else if (queue instanceof Queue && queue.out.hasLength(0)) { - let in$ = queue.in; - loop$queue = new Queue(toList([]), $list.reverse(in$)); - } else { - let in$ = queue.in; - let first = queue.out.head; - let rest = queue.out.tail; - let queue$1 = new Queue(in$, rest); - return new Ok([first, queue$1]); - } - } -} - -export function reverse(queue) { - return new Queue(queue.out, queue.in); -} - -function check_equal(loop$xs, loop$x_tail, loop$ys, loop$y_tail, loop$eq) { - while (true) { - let xs = loop$xs; - let x_tail = loop$x_tail; - let ys = loop$ys; - let y_tail = loop$y_tail; - let eq = loop$eq; - if (xs.hasLength(0) && - x_tail.hasLength(0) && - ys.hasLength(0) && - y_tail.hasLength(0)) { - return true; - } else if (xs.atLeastLength(1) && ys.atLeastLength(1)) { - let x = xs.head; - let xs$1 = xs.tail; - let y = ys.head; - let ys$1 = ys.tail; - let $ = eq(x, y); - if (!$) { - return false; - } else { - loop$xs = xs$1; - loop$x_tail = x_tail; - loop$ys = ys$1; - loop$y_tail = y_tail; - loop$eq = eq; - } - } else if (xs.hasLength(0) && x_tail.atLeastLength(1)) { - loop$xs = $list.reverse(x_tail); - loop$x_tail = toList([]); - loop$ys = ys; - loop$y_tail = y_tail; - loop$eq = eq; - } else if (ys.hasLength(0) && y_tail.atLeastLength(1)) { - loop$xs = xs; - loop$x_tail = x_tail; - loop$ys = $list.reverse(y_tail); - loop$y_tail = toList([]); - loop$eq = eq; - } else { - return false; - } - } -} - -export function is_logically_equal(a, b, element_is_equal) { - return check_equal(a.out, a.in, b.out, b.in, element_is_equal); -} - -export function is_equal(a, b) { - return check_equal( - a.out, - a.in, - b.out, - b.in, - (a, b) => { return isEqual(a, b); }, - ); -} diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/regex.mjs b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/regex.mjs deleted file mode 100644 index 84ae86149c8..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/regex.mjs +++ /dev/null @@ -1,55 +0,0 @@ -import { CustomType as $CustomType } from "../gleam.mjs"; -import * as $option from "../gleam/option.mjs"; -import { - compile_regex as do_compile, - regex_check as do_check, - regex_split as do_split, - regex_scan as do_scan, - regex_replace as replace, -} from "../gleam_stdlib.mjs"; - -export { replace }; - -export class Match extends $CustomType { - constructor(content, submatches) { - super(); - this.content = content; - this.submatches = submatches; - } -} - -export class CompileError extends $CustomType { - constructor(error, byte_index) { - super(); - this.error = error; - this.byte_index = byte_index; - } -} - -export class Options extends $CustomType { - constructor(case_insensitive, multi_line) { - super(); - this.case_insensitive = case_insensitive; - this.multi_line = multi_line; - } -} - -export function compile(pattern, options) { - return do_compile(pattern, options); -} - -export function from_string(pattern) { - return compile(pattern, new Options(false, false)); -} - -export function check(regex, string) { - return do_check(regex, string); -} - -export function split(regex, string) { - return do_split(regex, string); -} - -export function scan(regex, string) { - return do_scan(regex, string); -} diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/result.mjs b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/result.mjs deleted file mode 100644 index dfad5d5fbef..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/result.mjs +++ /dev/null @@ -1,182 +0,0 @@ -import { Ok, Error, toList, prepend as listPrepend } from "../gleam.mjs"; -import * as $list from "../gleam/list.mjs"; - -export function is_ok(result) { - if (!result.isOk()) { - return false; - } else { - return true; - } -} - -export function is_error(result) { - if (result.isOk()) { - return false; - } else { - return true; - } -} - -export function map(result, fun) { - if (result.isOk()) { - let x = result[0]; - return new Ok(fun(x)); - } else { - let e = result[0]; - return new Error(e); - } -} - -export function map_error(result, fun) { - if (result.isOk()) { - let x = result[0]; - return new Ok(x); - } else { - let error = result[0]; - return new Error(fun(error)); - } -} - -export function flatten(result) { - if (result.isOk()) { - let x = result[0]; - return x; - } else { - let error = result[0]; - return new Error(error); - } -} - -export function try$(result, fun) { - if (result.isOk()) { - let x = result[0]; - return fun(x); - } else { - let e = result[0]; - return new Error(e); - } -} - -export function then$(result, fun) { - return try$(result, fun); -} - -export function unwrap(result, default$) { - if (result.isOk()) { - let v = result[0]; - return v; - } else { - return default$; - } -} - -export function lazy_unwrap(result, default$) { - if (result.isOk()) { - let v = result[0]; - return v; - } else { - return default$(); - } -} - -export function unwrap_error(result, default$) { - if (result.isOk()) { - return default$; - } else { - let e = result[0]; - return e; - } -} - -export function unwrap_both(result) { - if (result.isOk()) { - let a = result[0]; - return a; - } else { - let a = result[0]; - return a; - } -} - -export function nil_error(result) { - return map_error(result, (_) => { return undefined; }); -} - -export function or(first, second) { - if (first.isOk()) { - return first; - } else { - return second; - } -} - -export function lazy_or(first, second) { - if (first.isOk()) { - return first; - } else { - return second(); - } -} - -export function all(results) { - return $list.try_map(results, (x) => { return x; }); -} - -function do_partition(loop$results, loop$oks, loop$errors) { - while (true) { - let results = loop$results; - let oks = loop$oks; - let errors = loop$errors; - if (results.hasLength(0)) { - return [oks, errors]; - } else if (results.atLeastLength(1) && results.head.isOk()) { - let a = results.head[0]; - let rest = results.tail; - loop$results = rest; - loop$oks = listPrepend(a, oks); - loop$errors = errors; - } else { - let e = results.head[0]; - let rest = results.tail; - loop$results = rest; - loop$oks = oks; - loop$errors = listPrepend(e, errors); - } - } -} - -export function partition(results) { - return do_partition(results, toList([]), toList([])); -} - -export function replace(result, value) { - if (result.isOk()) { - return new Ok(value); - } else { - let error = result[0]; - return new Error(error); - } -} - -export function replace_error(result, error) { - if (result.isOk()) { - let x = result[0]; - return new Ok(x); - } else { - return new Error(error); - } -} - -export function values(results) { - return $list.filter_map(results, (r) => { return r; }); -} - -export function try_recover(result, fun) { - if (result.isOk()) { - let value = result[0]; - return new Ok(value); - } else { - let error = result[0]; - return fun(error); - } -} diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/set.mjs b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/set.mjs deleted file mode 100644 index 8b91aeaab3b..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/set.mjs +++ /dev/null @@ -1,126 +0,0 @@ -import { CustomType as $CustomType, isEqual } from "../gleam.mjs"; -import * as $dict from "../gleam/dict.mjs"; -import * as $list from "../gleam/list.mjs"; -import * as $result from "../gleam/result.mjs"; - -class Set extends $CustomType { - constructor(dict) { - super(); - this.dict = dict; - } -} - -export function new$() { - return new Set($dict.new$()); -} - -export function size(set) { - return $dict.size(set.dict); -} - -export function is_empty(set) { - return isEqual(set, new$()); -} - -export function contains(set, member) { - let _pipe = set.dict; - let _pipe$1 = $dict.get(_pipe, member); - return $result.is_ok(_pipe$1); -} - -export function delete$(set, member) { - return new Set($dict.delete$(set.dict, member)); -} - -export function to_list(set) { - return $dict.keys(set.dict); -} - -export function fold(set, initial, reducer) { - return $dict.fold(set.dict, initial, (a, k, _) => { return reducer(a, k); }); -} - -export function filter(set, predicate) { - return new Set($dict.filter(set.dict, (m, _) => { return predicate(m); })); -} - -export function drop(set, disallowed) { - return $list.fold(disallowed, set, delete$); -} - -export function take(set, desired) { - return new Set($dict.take(set.dict, desired)); -} - -function order(first, second) { - let $ = $dict.size(first.dict) > $dict.size(second.dict); - if ($) { - return [first, second]; - } else { - return [second, first]; - } -} - -export function intersection(first, second) { - let $ = order(first, second); - let larger = $[0]; - let smaller = $[1]; - return take(larger, to_list(smaller)); -} - -export function difference(first, second) { - return drop(first, to_list(second)); -} - -export function is_subset(first, second) { - return isEqual(intersection(first, second), first); -} - -export function is_disjoint(first, second) { - return isEqual(intersection(first, second), new$()); -} - -export function each(set, fun) { - return fold( - set, - undefined, - (nil, member) => { - fun(member); - return nil; - }, - ); -} - -const token = undefined; - -export function insert(set, member) { - return new Set($dict.insert(set.dict, member, token)); -} - -export function from_list(members) { - let dict = $list.fold( - members, - $dict.new$(), - (m, k) => { return $dict.insert(m, k, token); }, - ); - return new Set(dict); -} - -export function map(set, fun) { - return fold( - set, - new$(), - (acc, member) => { return insert(acc, fun(member)); }, - ); -} - -export function union(first, second) { - let $ = order(first, second); - let larger = $[0]; - let smaller = $[1]; - return fold(smaller, larger, insert); -} - -export function symmetric_difference(first, second) { - return difference(union(first, second), intersection(first, second)); -} diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/string.mjs b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/string.mjs deleted file mode 100644 index a2c6a23bee8..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/string.mjs +++ /dev/null @@ -1,332 +0,0 @@ -import { - Ok, - Error, - prepend as listPrepend, - CustomType as $CustomType, - remainderInt, - divideInt, -} from "../gleam.mjs"; -import * as $list from "../gleam/list.mjs"; -import * as $option from "../gleam/option.mjs"; -import { None, Some } from "../gleam/option.mjs"; -import * as $order from "../gleam/order.mjs"; -import * as $string_builder from "../gleam/string_builder.mjs"; -import { - string_length as do_length, - lowercase as do_lowercase, - uppercase as do_uppercase, - less_than, - string_slice as do_slice, - crop_string as crop, - contains_string as contains, - starts_with as do_starts_with, - ends_with as do_ends_with, - split_once as do_split_once, - join as do_join, - trim as do_trim, - trim_left as do_trim_left, - trim_right as do_trim_right, - pop_grapheme as do_pop_grapheme, - graphemes as to_graphemes, - codepoint as unsafe_int_to_utf_codepoint, - string_to_codepoint_integer_list, - utf_codepoint_list_to_string as from_utf_codepoints, - utf_codepoint_to_int as do_utf_codepoint_to_int, - inspect as do_inspect, - byte_size, -} from "../gleam_stdlib.mjs"; - -export { byte_size, contains, crop, from_utf_codepoints, to_graphemes }; - -class Leading extends $CustomType {} - -class Trailing extends $CustomType {} - -class Both extends $CustomType {} - -export function is_empty(str) { - return str === ""; -} - -export function length(string) { - return do_length(string); -} - -function do_reverse(string) { - let _pipe = string; - let _pipe$1 = $string_builder.from_string(_pipe); - let _pipe$2 = $string_builder.reverse(_pipe$1); - return $string_builder.to_string(_pipe$2); -} - -export function reverse(string) { - return do_reverse(string); -} - -export function replace(string, pattern, substitute) { - let _pipe = string; - let _pipe$1 = $string_builder.from_string(_pipe); - let _pipe$2 = $string_builder.replace(_pipe$1, pattern, substitute); - return $string_builder.to_string(_pipe$2); -} - -export function lowercase(string) { - return do_lowercase(string); -} - -export function uppercase(string) { - return do_uppercase(string); -} - -export function compare(a, b) { - let $ = a === b; - if ($) { - return new $order.Eq(); - } else { - let $1 = less_than(a, b); - if ($1) { - return new $order.Lt(); - } else { - return new $order.Gt(); - } - } -} - -export function slice(string, idx, len) { - let $ = len < 0; - if ($) { - return ""; - } else { - let $1 = idx < 0; - if ($1) { - let translated_idx = length(string) + idx; - let $2 = translated_idx < 0; - if ($2) { - return ""; - } else { - return do_slice(string, translated_idx, len); - } - } else { - return do_slice(string, idx, len); - } - } -} - -export function drop_left(string, num_graphemes) { - let $ = num_graphemes < 0; - if ($) { - return string; - } else { - return slice(string, num_graphemes, length(string) - num_graphemes); - } -} - -export function drop_right(string, num_graphemes) { - let $ = num_graphemes < 0; - if ($) { - return string; - } else { - return slice(string, 0, length(string) - num_graphemes); - } -} - -export function starts_with(string, prefix) { - return do_starts_with(string, prefix); -} - -export function ends_with(string, suffix) { - return do_ends_with(string, suffix); -} - -export function split_once(string, substring) { - return do_split_once(string, substring); -} - -export function append(first, second) { - let _pipe = first; - let _pipe$1 = $string_builder.from_string(_pipe); - let _pipe$2 = $string_builder.append(_pipe$1, second); - return $string_builder.to_string(_pipe$2); -} - -export function concat(strings) { - let _pipe = strings; - let _pipe$1 = $string_builder.from_strings(_pipe); - return $string_builder.to_string(_pipe$1); -} - -function do_repeat(loop$string, loop$times, loop$acc) { - while (true) { - let string = loop$string; - let times = loop$times; - let acc = loop$acc; - let $ = times <= 0; - if ($) { - return acc; - } else { - loop$string = string; - loop$times = times - 1; - loop$acc = acc + string; - } - } -} - -export function repeat(string, times) { - return do_repeat(string, times, ""); -} - -export function join(strings, separator) { - return do_join(strings, separator); -} - -function padding(size, pad_string) { - let pad_string_length = length(pad_string); - let num_pads = divideInt(size, pad_string_length); - let extra = remainderInt(size, pad_string_length); - return repeat(pad_string, num_pads) + slice(pad_string, 0, extra); -} - -export function pad_left(string, desired_length, pad_string) { - let current_length = length(string); - let to_pad_length = desired_length - current_length; - let $ = to_pad_length <= 0; - if ($) { - return string; - } else { - return padding(to_pad_length, pad_string) + string; - } -} - -export function pad_right(string, desired_length, pad_string) { - let current_length = length(string); - let to_pad_length = desired_length - current_length; - let $ = to_pad_length <= 0; - if ($) { - return string; - } else { - return string + padding(to_pad_length, pad_string); - } -} - -export function trim(string) { - return do_trim(string); -} - -export function trim_left(string) { - return do_trim_left(string); -} - -export function trim_right(string) { - return do_trim_right(string); -} - -export function pop_grapheme(string) { - return do_pop_grapheme(string); -} - -function do_to_graphemes(loop$string, loop$acc) { - while (true) { - let string = loop$string; - let acc = loop$acc; - let $ = pop_grapheme(string); - if ($.isOk()) { - let grapheme = $[0][0]; - let rest = $[0][1]; - loop$string = rest; - loop$acc = listPrepend(grapheme, acc); - } else { - return acc; - } - } -} - -export function split(x, substring) { - if (substring === "") { - return to_graphemes(x); - } else { - let _pipe = x; - let _pipe$1 = $string_builder.from_string(_pipe); - let _pipe$2 = $string_builder.split(_pipe$1, substring); - return $list.map(_pipe$2, $string_builder.to_string); - } -} - -function do_to_utf_codepoints(string) { - let _pipe = string; - let _pipe$1 = string_to_codepoint_integer_list(_pipe); - return $list.map(_pipe$1, unsafe_int_to_utf_codepoint); -} - -export function to_utf_codepoints(string) { - return do_to_utf_codepoints(string); -} - -export function utf_codepoint(value) { - if (value > 1_114_111) { - let i = value; - return new Error(undefined); - } else if (value === 65_534) { - return new Error(undefined); - } else if (value === 65_535) { - return new Error(undefined); - } else if ((value >= 55_296) && (value <= 57_343)) { - let i = value; - return new Error(undefined); - } else { - let i = value; - return new Ok(unsafe_int_to_utf_codepoint(i)); - } -} - -export function utf_codepoint_to_int(cp) { - return do_utf_codepoint_to_int(cp); -} - -export function to_option(string) { - if (string === "") { - return new None(); - } else { - return new Some(string); - } -} - -export function first(string) { - let $ = pop_grapheme(string); - if ($.isOk()) { - let first$1 = $[0][0]; - return new Ok(first$1); - } else { - let e = $[0]; - return new Error(e); - } -} - -export function last(string) { - let $ = pop_grapheme(string); - if ($.isOk() && $[0][1] === "") { - let first$1 = $[0][0]; - return new Ok(first$1); - } else if ($.isOk()) { - let rest = $[0][1]; - return new Ok(slice(rest, -1, 1)); - } else { - let e = $[0]; - return new Error(e); - } -} - -export function capitalise(string) { - let $ = pop_grapheme(string); - if ($.isOk()) { - let first$1 = $[0][0]; - let rest = $[0][1]; - return append(uppercase(first$1), lowercase(rest)); - } else { - return ""; - } -} - -export function inspect(term) { - let _pipe = do_inspect(term); - return $string_builder.to_string(_pipe); -} diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/string_builder.mjs b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/string_builder.mjs deleted file mode 100644 index 413b56297f5..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/string_builder.mjs +++ /dev/null @@ -1,97 +0,0 @@ -import { toList, CustomType as $CustomType, isEqual } from "../gleam.mjs"; -import * as $list from "../gleam/list.mjs"; -import { - add as do_append, - concat as do_from_strings, - concat as do_concat, - identity as do_from_string, - identity as do_to_string, - length as do_byte_size, - lowercase as do_lowercase, - uppercase as do_uppercase, - graphemes as do_to_graphemes, - split as do_split, - string_replace as replace, -} from "../gleam_stdlib.mjs"; - -export { replace }; - -class All extends $CustomType {} - -export function prepend_builder(builder, prefix) { - return do_append(prefix, builder); -} - -export function append_builder(builder, suffix) { - return do_append(builder, suffix); -} - -export function new$() { - return do_from_strings(toList([])); -} - -export function from_strings(strings) { - return do_from_strings(strings); -} - -export function concat(builders) { - return do_concat(builders); -} - -export function from_string(string) { - return do_from_string(string); -} - -export function prepend(builder, prefix) { - return append_builder(from_string(prefix), builder); -} - -export function append(builder, second) { - return append_builder(builder, from_string(second)); -} - -export function to_string(builder) { - return do_to_string(builder); -} - -export function byte_size(builder) { - return do_byte_size(builder); -} - -export function join(builders, sep) { - let _pipe = builders; - let _pipe$1 = $list.intersperse(_pipe, from_string(sep)); - return concat(_pipe$1); -} - -export function lowercase(builder) { - return do_lowercase(builder); -} - -export function uppercase(builder) { - return do_uppercase(builder); -} - -function do_reverse(builder) { - let _pipe = builder; - let _pipe$1 = to_string(_pipe); - let _pipe$2 = do_to_graphemes(_pipe$1); - let _pipe$3 = $list.reverse(_pipe$2); - return from_strings(_pipe$3); -} - -export function reverse(builder) { - return do_reverse(builder); -} - -export function split(iodata, pattern) { - return do_split(iodata, pattern); -} - -export function is_equal(a, b) { - return isEqual(a, b); -} - -export function is_empty(builder) { - return isEqual(from_string(""), builder); -} diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/uri.mjs b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/uri.mjs deleted file mode 100644 index a79019c55e6..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam/uri.mjs +++ /dev/null @@ -1,433 +0,0 @@ -import { - Ok, - Error, - toList, - prepend as listPrepend, - CustomType as $CustomType, - isEqual, -} from "../gleam.mjs"; -import * as $int from "../gleam/int.mjs"; -import * as $list from "../gleam/list.mjs"; -import * as $option from "../gleam/option.mjs"; -import { None, Some } from "../gleam/option.mjs"; -import * as $pair from "../gleam/pair.mjs"; -import * as $regex from "../gleam/regex.mjs"; -import * as $result from "../gleam/result.mjs"; -import * as $string from "../gleam/string.mjs"; -import * as $string_builder from "../gleam/string_builder.mjs"; -import { - parse_query as do_parse_query, - percent_encode as do_percent_encode, - percent_decode as do_percent_decode, -} from "../gleam_stdlib.mjs"; - -export class Uri extends $CustomType { - constructor(scheme, userinfo, host, port, path, query, fragment) { - super(); - this.scheme = scheme; - this.userinfo = userinfo; - this.host = host; - this.port = port; - this.path = path; - this.query = query; - this.fragment = fragment; - } -} - -function regex_submatches(pattern, string) { - let _pipe = pattern; - let _pipe$1 = $regex.compile(_pipe, new $regex.Options(true, false)); - let _pipe$2 = $result.nil_error(_pipe$1); - let _pipe$3 = $result.map( - _pipe$2, - (_capture) => { return $regex.scan(_capture, string); }, - ); - let _pipe$4 = $result.try$(_pipe$3, $list.first); - let _pipe$5 = $result.map(_pipe$4, (m) => { return m.submatches; }); - return $result.unwrap(_pipe$5, toList([])); -} - -function noneify_query(x) { - if (x instanceof None) { - return new None(); - } else { - let x$1 = x[0]; - let $ = $string.pop_grapheme(x$1); - if ($.isOk() && $[0][0] === "?") { - let query = $[0][1]; - return new Some(query); - } else { - return new None(); - } - } -} - -function noneify_empty_string(x) { - if (x instanceof Some && x[0] === "") { - return new None(); - } else if (x instanceof None) { - return new None(); - } else { - return x; - } -} - -function extra_required(loop$list, loop$remaining) { - while (true) { - let list = loop$list; - let remaining = loop$remaining; - if (remaining === 0) { - return 0; - } else if (list.hasLength(0)) { - return remaining; - } else { - let rest = list.tail; - loop$list = rest; - loop$remaining = remaining - 1; - } - } -} - -function pad_list(list, size) { - let _pipe = list; - return $list.append( - _pipe, - $list.repeat(new None(), extra_required(list, size)), - ); -} - -function split_authority(authority) { - let $ = $option.unwrap(authority, ""); - if ($ === "") { - return [new None(), new None(), new None()]; - } else if ($ === "//") { - return [new None(), new Some(""), new None()]; - } else { - let authority$1 = $; - let matches = (() => { - let _pipe = "^(//)?((.*)@)?(\\[[a-zA-Z0-9:.]*\\]|[^:]*)(:(\\d*))?"; - let _pipe$1 = regex_submatches(_pipe, authority$1); - return pad_list(_pipe$1, 6); - })(); - if (matches.hasLength(6)) { - let userinfo = matches.tail.tail.head; - let host = matches.tail.tail.tail.head; - let port = matches.tail.tail.tail.tail.tail.head; - let userinfo$1 = noneify_empty_string(userinfo); - let host$1 = noneify_empty_string(host); - let port$1 = (() => { - let _pipe = port; - let _pipe$1 = $option.unwrap(_pipe, ""); - let _pipe$2 = $int.parse(_pipe$1); - return $option.from_result(_pipe$2); - })(); - return [userinfo$1, host$1, port$1]; - } else { - return [new None(), new None(), new None()]; - } - } -} - -function do_parse(uri_string) { - let pattern = "^(([a-z][a-z0-9\\+\\-\\.]*):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#.*)?"; - let matches = (() => { - let _pipe = pattern; - let _pipe$1 = regex_submatches(_pipe, uri_string); - return pad_list(_pipe$1, 8); - })(); - let $ = (() => { - if (matches.hasLength(8)) { - let scheme = matches.tail.head; - let authority_with_slashes = matches.tail.tail.head; - let path = matches.tail.tail.tail.tail.head; - let query_with_question_mark = matches.tail.tail.tail.tail.tail.head; - let fragment = matches.tail.tail.tail.tail.tail.tail.tail.head; - return [ - scheme, - authority_with_slashes, - path, - query_with_question_mark, - fragment, - ]; - } else { - return [new None(), new None(), new None(), new None(), new None()]; - } - })(); - let scheme = $[0]; - let authority = $[1]; - let path = $[2]; - let query = $[3]; - let fragment = $[4]; - let scheme$1 = noneify_empty_string(scheme); - let path$1 = $option.unwrap(path, ""); - let query$1 = noneify_query(query); - let $1 = split_authority(authority); - let userinfo = $1[0]; - let host = $1[1]; - let port = $1[2]; - let fragment$1 = (() => { - let _pipe = fragment; - let _pipe$1 = $option.to_result(_pipe, undefined); - let _pipe$2 = $result.try$(_pipe$1, $string.pop_grapheme); - let _pipe$3 = $result.map(_pipe$2, $pair.second); - return $option.from_result(_pipe$3); - })(); - let scheme$2 = (() => { - let _pipe = scheme$1; - let _pipe$1 = noneify_empty_string(_pipe); - return $option.map(_pipe$1, $string.lowercase); - })(); - return new Ok( - new Uri(scheme$2, userinfo, host, port, path$1, query$1, fragment$1), - ); -} - -export function parse(uri_string) { - return do_parse(uri_string); -} - -export function parse_query(query) { - return do_parse_query(query); -} - -export function percent_encode(value) { - return do_percent_encode(value); -} - -function query_pair(pair) { - return $string_builder.from_strings( - toList([percent_encode(pair[0]), "=", percent_encode(pair[1])]), - ); -} - -export function query_to_string(query) { - let _pipe = query; - let _pipe$1 = $list.map(_pipe, query_pair); - let _pipe$2 = $list.intersperse(_pipe$1, $string_builder.from_string("&")); - let _pipe$3 = $string_builder.concat(_pipe$2); - return $string_builder.to_string(_pipe$3); -} - -export function percent_decode(value) { - return do_percent_decode(value); -} - -function do_remove_dot_segments(loop$input, loop$accumulator) { - while (true) { - let input = loop$input; - let accumulator = loop$accumulator; - if (input.hasLength(0)) { - return $list.reverse(accumulator); - } else { - let segment = input.head; - let rest = input.tail; - let accumulator$1 = (() => { - if (segment === "") { - let accumulator$1 = accumulator; - return accumulator$1; - } else if (segment === ".") { - let accumulator$1 = accumulator; - return accumulator$1; - } else if (segment === ".." && accumulator.hasLength(0)) { - return toList([]); - } else if (segment === ".." && accumulator.atLeastLength(1)) { - let accumulator$1 = accumulator.tail; - return accumulator$1; - } else { - let segment$1 = segment; - let accumulator$1 = accumulator; - return listPrepend(segment$1, accumulator$1); - } - })(); - loop$input = rest; - loop$accumulator = accumulator$1; - } - } -} - -function remove_dot_segments(input) { - return do_remove_dot_segments(input, toList([])); -} - -export function path_segments(path) { - return remove_dot_segments($string.split(path, "/")); -} - -export function to_string(uri) { - let parts = (() => { - let $ = uri.fragment; - if ($ instanceof Some) { - let fragment = $[0]; - return toList(["#", fragment]); - } else { - return toList([]); - } - })(); - let parts$1 = (() => { - let $ = uri.query; - if ($ instanceof Some) { - let query = $[0]; - return listPrepend("?", listPrepend(query, parts)); - } else { - return parts; - } - })(); - let parts$2 = listPrepend(uri.path, parts$1); - let parts$3 = (() => { - let $ = uri.host; - let $1 = $string.starts_with(uri.path, "/"); - if ($ instanceof Some && !$1 && ($[0] !== "")) { - let host = $[0]; - return listPrepend("/", parts$2); - } else { - return parts$2; - } - })(); - let parts$4 = (() => { - let $ = uri.host; - let $1 = uri.port; - if ($ instanceof Some && $1 instanceof Some) { - let port = $1[0]; - return listPrepend(":", listPrepend($int.to_string(port), parts$3)); - } else { - return parts$3; - } - })(); - let parts$5 = (() => { - let $ = uri.scheme; - let $1 = uri.userinfo; - let $2 = uri.host; - if ($ instanceof Some && $1 instanceof Some && $2 instanceof Some) { - let s = $[0]; - let u = $1[0]; - let h = $2[0]; - return listPrepend( - s, - listPrepend( - "://", - listPrepend(u, listPrepend("@", listPrepend(h, parts$4))), - ), - ); - } else if ($ instanceof Some && $1 instanceof None && $2 instanceof Some) { - let s = $[0]; - let h = $2[0]; - return listPrepend(s, listPrepend("://", listPrepend(h, parts$4))); - } else if ($ instanceof Some && $1 instanceof Some && $2 instanceof None) { - let s = $[0]; - return listPrepend(s, listPrepend(":", parts$4)); - } else if ($ instanceof Some && $1 instanceof None && $2 instanceof None) { - let s = $[0]; - return listPrepend(s, listPrepend(":", parts$4)); - } else if ($ instanceof None && $1 instanceof None && $2 instanceof Some) { - let h = $2[0]; - return listPrepend("//", listPrepend(h, parts$4)); - } else { - return parts$4; - } - })(); - return $string.concat(parts$5); -} - -export function origin(uri) { - let scheme = uri.scheme; - let host = uri.host; - let port = uri.port; - if (host instanceof Some && - scheme instanceof Some && - scheme[0] === "https" && - (isEqual(port, new Some(443)))) { - let h = host[0]; - return new Ok($string.concat(toList(["https://", h]))); - } else if (host instanceof Some && - scheme instanceof Some && - scheme[0] === "http" && - (isEqual(port, new Some(80)))) { - let h = host[0]; - return new Ok($string.concat(toList(["http://", h]))); - } else if (host instanceof Some && - scheme instanceof Some && - ((scheme[0] === "http") || (scheme[0] === "https"))) { - let h = host[0]; - let s = scheme[0]; - if (port instanceof Some) { - let p = port[0]; - return new Ok( - $string.concat(toList([s, "://", h, ":", $int.to_string(p)])), - ); - } else { - return new Ok($string.concat(toList([s, "://", h]))); - } - } else { - return new Error(undefined); - } -} - -function drop_last(elements) { - return $list.take(elements, $list.length(elements) - 1); -} - -function join_segments(segments) { - return $string.join(listPrepend("", segments), "/"); -} - -export function merge(base, relative) { - if (base instanceof Uri && - base.scheme instanceof Some && - base.host instanceof Some) { - if (relative instanceof Uri && relative.host instanceof Some) { - let path = (() => { - let _pipe = $string.split(relative.path, "/"); - let _pipe$1 = remove_dot_segments(_pipe); - return join_segments(_pipe$1); - })(); - let resolved = new Uri( - $option.or(relative.scheme, base.scheme), - new None(), - relative.host, - $option.or(relative.port, base.port), - path, - relative.query, - relative.fragment, - ); - return new Ok(resolved); - } else { - let $ = (() => { - let $1 = relative.path; - if ($1 === "") { - return [base.path, $option.or(relative.query, base.query)]; - } else { - let path_segments$1 = (() => { - let $2 = $string.starts_with(relative.path, "/"); - if ($2) { - return $string.split(relative.path, "/"); - } else { - let _pipe = $string.split(base.path, "/"); - let _pipe$1 = drop_last(_pipe); - return $list.append(_pipe$1, $string.split(relative.path, "/")); - } - })(); - let path = (() => { - let _pipe = path_segments$1; - let _pipe$1 = remove_dot_segments(_pipe); - return join_segments(_pipe$1); - })(); - return [path, relative.query]; - } - })(); - let new_path = $[0]; - let new_query = $[1]; - let resolved = new Uri( - base.scheme, - new None(), - base.host, - base.port, - new_path, - new_query, - relative.fragment, - ); - return new Ok(resolved); - } - } else { - return new Error(undefined); - } -} diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@bit_array.erl b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@bit_array.erl deleted file mode 100644 index d5cba7bcebd..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@bit_array.erl +++ /dev/null @@ -1,213 +0,0 @@ --module(gleam@bit_array). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([from_string/1, byte_size/1, slice/3, is_utf8/1, to_string/1, concat/1, append/2, base64_encode/2, base64_decode/1, base64_url_encode/2, base64_url_decode/1, base16_encode/1, base16_decode/1, inspect/1, compare/2]). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bit_array.gleam", 11). --spec from_string(binary()) -> bitstring(). -from_string(X) -> - gleam_stdlib:identity(X). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bit_array.gleam", 17). --spec byte_size(bitstring()) -> integer(). -byte_size(X) -> - erlang:byte_size(X). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bit_array.gleam", 42). --spec slice(bitstring(), integer(), integer()) -> {ok, bitstring()} | - {error, nil}. -slice(String, Position, Length) -> - gleam_stdlib:bit_array_slice(String, Position, Length). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bit_array.gleam", 55). --spec do_is_utf8(bitstring()) -> boolean(). -do_is_utf8(Bits) -> - case Bits of - <<>> -> - true; - - <<_/utf8, Rest/binary>> -> - do_is_utf8(Rest); - - _ -> - false - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/bit_array.gleam", 50). --spec is_utf8(bitstring()) -> boolean(). -is_utf8(Bits) -> - do_is_utf8(Bits). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bit_array.gleam", 83). --spec do_to_string(bitstring()) -> {ok, binary()} | {error, nil}. -do_to_string(Bits) -> - case is_utf8(Bits) of - true -> - {ok, gleam_stdlib:identity(Bits)}; - - false -> - {error, nil} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/bit_array.gleam", 75). --spec to_string(bitstring()) -> {ok, binary()} | {error, nil}. -to_string(Bits) -> - do_to_string(Bits). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bit_array.gleam", 101). --spec concat(list(bitstring())) -> bitstring(). -concat(Bit_arrays) -> - gleam_stdlib:bit_array_concat(Bit_arrays). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bit_array.gleam", 28). --spec append(bitstring(), bitstring()) -> bitstring(). -append(First, Second) -> - gleam_stdlib:bit_array_concat([First, Second]). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bit_array.gleam", 107). --spec base64_encode(bitstring(), boolean()) -> binary(). -base64_encode(Input, Padding) -> - gleam_stdlib:bit_array_base64_encode(Input, Padding). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bit_array.gleam", 111). --spec base64_decode(binary()) -> {ok, bitstring()} | {error, nil}. -base64_decode(Encoded) -> - Padded = case erlang:byte_size(gleam_stdlib:identity(Encoded)) rem 4 of - 0 -> - Encoded; - - N -> - gleam@string:append( - Encoded, - gleam@string:repeat(<<"="/utf8>>, 4 - N) - ) - end, - gleam_stdlib:base_decode64(Padded). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bit_array.gleam", 125). --spec base64_url_encode(bitstring(), boolean()) -> binary(). -base64_url_encode(Input, Padding) -> - _pipe = gleam_stdlib:bit_array_base64_encode(Input, Padding), - _pipe@1 = gleam@string:replace(_pipe, <<"+"/utf8>>, <<"-"/utf8>>), - gleam@string:replace(_pipe@1, <<"/"/utf8>>, <<"_"/utf8>>). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bit_array.gleam", 133). --spec base64_url_decode(binary()) -> {ok, bitstring()} | {error, nil}. -base64_url_decode(Encoded) -> - _pipe = Encoded, - _pipe@1 = gleam@string:replace(_pipe, <<"-"/utf8>>, <<"+"/utf8>>), - _pipe@2 = gleam@string:replace(_pipe@1, <<"_"/utf8>>, <<"/"/utf8>>), - base64_decode(_pipe@2). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bit_array.gleam", 142). --spec base16_encode(bitstring()) -> binary(). -base16_encode(Input) -> - binary:encode_hex(Input). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bit_array.gleam", 146). --spec base16_decode(binary()) -> {ok, bitstring()} | {error, nil}. -base16_decode(Input) -> - gleam_stdlib:base16_decode(Input). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bit_array.gleam", 165). --spec do_inspect(bitstring(), binary()) -> binary(). -do_inspect(Input, Accumulator) -> - case Input of - <<>> -> - Accumulator; - - <> -> - <<<>/binary, - ":size(1)"/utf8>>; - - <> -> - <<<>/binary, - ":size(2)"/utf8>>; - - <> -> - <<<>/binary, - ":size(3)"/utf8>>; - - <> -> - <<<>/binary, - ":size(4)"/utf8>>; - - <> -> - <<<>/binary, - ":size(5)"/utf8>>; - - <> -> - <<<>/binary, - ":size(6)"/utf8>>; - - <> -> - <<<>/binary, - ":size(7)"/utf8>>; - - <> -> - Suffix = case Rest of - <<>> -> - <<""/utf8>>; - - _ -> - <<", "/utf8>> - end, - Accumulator@1 = <<<>/binary, - Suffix/binary>>, - do_inspect(Rest, Accumulator@1); - - _ -> - Accumulator - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/bit_array.gleam", 160). --spec inspect(bitstring()) -> binary(). -inspect(Input) -> - <<(do_inspect(Input, <<"<<"/utf8>>))/binary, ">>"/utf8>>. - --file("/Users/louis/src/gleam/stdlib/src/gleam/bit_array.gleam", 210). --spec compare(bitstring(), bitstring()) -> gleam@order:order(). -compare(A, B) -> - case {A, B} of - {<>, - <>} -> - case {First_byte, Second_byte} of - {F, S} when F > S -> - gt; - - {F@1, S@1} when F@1 < S@1 -> - lt; - - {_, _} -> - compare(First_rest, Second_rest) - end; - - {<<>>, <<>>} -> - eq; - - {_, <<>>} -> - gt; - - {<<>>, _} -> - lt; - - {First, Second} -> - case {gleam_stdlib:bit_array_to_int_and_size(First), - gleam_stdlib:bit_array_to_int_and_size(Second)} of - {{A@1, _}, {B@1, _}} when A@1 > B@1 -> - gt; - - {{A@2, _}, {B@2, _}} when A@2 < B@2 -> - lt; - - {{_, Size_a}, {_, Size_b}} when Size_a > Size_b -> - gt; - - {{_, Size_a@1}, {_, Size_b@1}} when Size_a@1 < Size_b@1 -> - lt; - - {_, _} -> - eq - end - end. diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@bool.erl b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@bool.erl deleted file mode 100644 index 16b0a9df238..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@bool.erl +++ /dev/null @@ -1,100 +0,0 @@ --module(gleam@bool). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export(['and'/2, 'or'/2, negate/1, nor/2, nand/2, exclusive_or/2, exclusive_nor/2, compare/2, to_int/1, to_string/1, guard/3, lazy_guard/3]). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bool.gleam", 33). --spec 'and'(boolean(), boolean()) -> boolean(). -'and'(A, B) -> - A andalso B. - --file("/Users/louis/src/gleam/stdlib/src/gleam/bool.gleam", 59). --spec 'or'(boolean(), boolean()) -> boolean(). -'or'(A, B) -> - A orelse B. - --file("/Users/louis/src/gleam/stdlib/src/gleam/bool.gleam", 79). --spec negate(boolean()) -> boolean(). -negate(Bool) -> - not Bool. - --file("/Users/louis/src/gleam/stdlib/src/gleam/bool.gleam", 107). --spec nor(boolean(), boolean()) -> boolean(). -nor(A, B) -> - not (A orelse B). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bool.gleam", 135). --spec nand(boolean(), boolean()) -> boolean(). -nand(A, B) -> - not (A andalso B). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bool.gleam", 163). --spec exclusive_or(boolean(), boolean()) -> boolean(). -exclusive_or(A, B) -> - A /= B. - --file("/Users/louis/src/gleam/stdlib/src/gleam/bool.gleam", 191). --spec exclusive_nor(boolean(), boolean()) -> boolean(). -exclusive_nor(A, B) -> - A =:= B. - --file("/Users/louis/src/gleam/stdlib/src/gleam/bool.gleam", 206). --spec compare(boolean(), boolean()) -> gleam@order:order(). -compare(A, B) -> - case {A, B} of - {true, true} -> - eq; - - {true, false} -> - gt; - - {false, false} -> - eq; - - {false, true} -> - lt - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/bool.gleam", 229). --spec to_int(boolean()) -> integer(). -to_int(Bool) -> - case Bool of - false -> - 0; - - true -> - 1 - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/bool.gleam", 250). --spec to_string(boolean()) -> binary(). -to_string(Bool) -> - case Bool of - false -> - <<"False"/utf8>>; - - true -> - <<"True"/utf8>> - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/bool.gleam", 309). --spec guard(boolean(), BVG, fun(() -> BVG)) -> BVG. -guard(Requirement, Consequence, Alternative) -> - case Requirement of - true -> - Consequence; - - false -> - Alternative() - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/bool.gleam", 350). --spec lazy_guard(boolean(), fun(() -> BVH), fun(() -> BVH)) -> BVH. -lazy_guard(Requirement, Consequence, Alternative) -> - case Requirement of - true -> - Consequence(); - - false -> - Alternative() - end. diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@bytes_builder.erl b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@bytes_builder.erl deleted file mode 100644 index a487e08aca5..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@bytes_builder.erl +++ /dev/null @@ -1,102 +0,0 @@ --module(gleam@bytes_builder). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([append_builder/2, prepend_builder/2, concat/1, new/0, from_string/1, prepend_string/2, append_string/2, from_string_builder/1, from_bit_array/1, prepend/2, append/2, concat_bit_arrays/1, to_bit_array/1, byte_size/1]). --export_type([bytes_builder/0]). - --opaque bytes_builder() :: {bytes, bitstring()} | - {text, gleam@string_builder:string_builder()} | - {many, list(bytes_builder())}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/bytes_builder.gleam", 72). --spec append_builder(bytes_builder(), bytes_builder()) -> bytes_builder(). -append_builder(First, Second) -> - gleam_stdlib:iodata_append(First, Second). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bytes_builder.gleam", 60). --spec prepend_builder(bytes_builder(), bytes_builder()) -> bytes_builder(). -prepend_builder(Second, First) -> - gleam_stdlib:iodata_append(First, Second). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bytes_builder.gleam", 111). --spec concat(list(bytes_builder())) -> bytes_builder(). -concat(Builders) -> - gleam_stdlib:identity(Builders). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bytes_builder.gleam", 36). --spec new() -> bytes_builder(). -new() -> - gleam_stdlib:identity([]). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bytes_builder.gleam", 132). --spec from_string(binary()) -> bytes_builder(). -from_string(String) -> - gleam_stdlib:wrap_list(String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bytes_builder.gleam", 87). --spec prepend_string(bytes_builder(), binary()) -> bytes_builder(). -prepend_string(Second, First) -> - gleam_stdlib:iodata_append(gleam_stdlib:wrap_list(First), Second). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bytes_builder.gleam", 99). --spec append_string(bytes_builder(), binary()) -> bytes_builder(). -append_string(First, Second) -> - gleam_stdlib:iodata_append(First, gleam_stdlib:wrap_list(Second)). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bytes_builder.gleam", 142). --spec from_string_builder(gleam@string_builder:string_builder()) -> bytes_builder(). -from_string_builder(Builder) -> - gleam_stdlib:wrap_list(Builder). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bytes_builder.gleam", 151). --spec from_bit_array(bitstring()) -> bytes_builder(). -from_bit_array(Bits) -> - gleam_stdlib:wrap_list(Bits). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bytes_builder.gleam", 44). --spec prepend(bytes_builder(), bitstring()) -> bytes_builder(). -prepend(Second, First) -> - gleam_stdlib:iodata_append(gleam_stdlib:wrap_list(First), Second). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bytes_builder.gleam", 52). --spec append(bytes_builder(), bitstring()) -> bytes_builder(). -append(First, Second) -> - gleam_stdlib:iodata_append(First, gleam_stdlib:wrap_list(Second)). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bytes_builder.gleam", 120). --spec concat_bit_arrays(list(bitstring())) -> bytes_builder(). -concat_bit_arrays(Bits) -> - gleam_stdlib:identity(Bits). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bytes_builder.gleam", 170). --spec to_list(list(list(bytes_builder())), list(bitstring())) -> list(bitstring()). -to_list(Stack, Acc) -> - case Stack of - [] -> - Acc; - - [[] | Remaining_stack] -> - to_list(Remaining_stack, Acc); - - [[{bytes, Bits} | Rest] | Remaining_stack@1] -> - to_list([Rest | Remaining_stack@1], [Bits | Acc]); - - [[{text, Builder} | Rest@1] | Remaining_stack@2] -> - Bits@1 = gleam_stdlib:identity( - gleam@string_builder:to_string(Builder) - ), - to_list([Rest@1 | Remaining_stack@2], [Bits@1 | Acc]); - - [[{many, Builders} | Rest@2] | Remaining_stack@3] -> - to_list([Builders, Rest@2 | Remaining_stack@3], Acc) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/bytes_builder.gleam", 163). --spec to_bit_array(bytes_builder()) -> bitstring(). -to_bit_array(Builder) -> - erlang:list_to_bitstring(Builder). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bytes_builder.gleam", 197). --spec byte_size(bytes_builder()) -> integer(). -byte_size(Builder) -> - erlang:iolist_size(Builder). diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@dict.erl b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@dict.erl deleted file mode 100644 index 658b859d62b..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@dict.erl +++ /dev/null @@ -1,224 +0,0 @@ --module(gleam@dict). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([size/1, to_list/1, new/0, is_empty/1, get/2, has_key/2, insert/3, from_list/1, keys/1, values/1, take/2, merge/2, delete/2, drop/2, upsert/3, fold/3, map_values/2, filter/2, each/2, combine/3]). --export_type([dict/2]). - --type dict(KM, KN) :: any() | {gleam_phantom, KM, KN}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 36). --spec size(dict(any(), any())) -> integer(). -size(Dict) -> - maps:size(Dict). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 80). --spec to_list(dict(KW, KX)) -> list({KW, KX}). -to_list(Dict) -> - maps:to_list(Dict). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 127). --spec new() -> dict(any(), any()). -new() -> - maps:new(). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 52). --spec is_empty(dict(any(), any())) -> boolean(). -is_empty(Dict) -> - Dict =:= new(). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 152). --spec get(dict(MD, ME), MD) -> {ok, ME} | {error, nil}. -get(From, Get) -> - gleam_stdlib:map_get(From, Get). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 116). --spec has_key(dict(LN, any()), LN) -> boolean(). -has_key(Dict, Key) -> - maps:is_key(Key, Dict). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 177). --spec insert(dict(MP, MQ), MP, MQ) -> dict(MP, MQ). -insert(Dict, Key, Value) -> - maps:put(Key, Value, Dict). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 92). --spec fold_list_of_pair(list({LG, LH}), dict(LG, LH)) -> dict(LG, LH). -fold_list_of_pair(List, Initial) -> - case List of - [] -> - Initial; - - [X | Rest] -> - fold_list_of_pair( - Rest, - insert(Initial, erlang:element(1, X), erlang:element(2, X)) - ) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 88). --spec from_list(list({LB, LC})) -> dict(LB, LC). -from_list(List) -> - maps:from_list(List). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 229). --spec reverse_and_concat(list(NZ), list(NZ)) -> list(NZ). -reverse_and_concat(Remaining, Accumulator) -> - case Remaining of - [] -> - Accumulator; - - [Item | Rest] -> - reverse_and_concat(Rest, [Item | Accumulator]) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 236). --spec do_keys_acc(list({OD, any()}), list(OD)) -> list(OD). -do_keys_acc(List, Acc) -> - case List of - [] -> - reverse_and_concat(Acc, []); - - [First | Rest] -> - do_keys_acc(Rest, [erlang:element(1, First) | Acc]) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 219). --spec keys(dict(NP, any())) -> list(NP). -keys(Dict) -> - maps:keys(Dict). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 266). --spec do_values_acc(list({any(), OT}), list(OT)) -> list(OT). -do_values_acc(List, Acc) -> - case List of - [] -> - reverse_and_concat(Acc, []); - - [First | Rest] -> - do_values_acc(Rest, [erlang:element(2, First) | Acc]) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 256). --spec values(dict(any(), OJ)) -> list(OJ). -values(Dict) -> - maps:values(Dict). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 335). --spec insert_taken(dict(PX, PY), list(PX), dict(PX, PY)) -> dict(PX, PY). -insert_taken(Dict, Desired_keys, Acc) -> - Insert = fun(Taken, Key) -> case get(Dict, Key) of - {ok, Value} -> - insert(Taken, Key, Value); - - _ -> - Taken - end end, - case Desired_keys of - [] -> - Acc; - - [First | Rest] -> - insert_taken(Dict, Rest, Insert(Acc, First)) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 326). --spec take(dict(PJ, PK), list(PJ)) -> dict(PJ, PK). -take(Dict, Desired_keys) -> - maps:with(Desired_keys, Dict). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 377). --spec insert_pair(dict(QW, QX), {QW, QX}) -> dict(QW, QX). -insert_pair(Dict, Pair) -> - insert(Dict, erlang:element(1, Pair), erlang:element(2, Pair)). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 381). --spec fold_inserts(list({RC, RD}), dict(RC, RD)) -> dict(RC, RD). -fold_inserts(New_entries, Dict) -> - case New_entries of - [] -> - Dict; - - [First | Rest] -> - fold_inserts(Rest, insert_pair(Dict, First)) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 366). --spec merge(dict(QG, QH), dict(QG, QH)) -> dict(QG, QH). -merge(Dict, New_entries) -> - maps:merge(Dict, New_entries). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 403). --spec delete(dict(RJ, RK), RJ) -> dict(RJ, RK). -delete(Dict, Key) -> - maps:remove(Key, Dict). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 431). --spec drop(dict(RV, RW), list(RV)) -> dict(RV, RW). -drop(Dict, Disallowed_keys) -> - case Disallowed_keys of - [] -> - Dict; - - [First | Rest] -> - drop(delete(Dict, First), Rest) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 461). --spec upsert(dict(SC, SD), SC, fun((gleam@option:option(SD)) -> SD)) -> dict(SC, SD). -upsert(Dict, Key, Fun) -> - _pipe = Dict, - _pipe@1 = get(_pipe, Key), - _pipe@2 = gleam@option:from_result(_pipe@1), - _pipe@3 = Fun(_pipe@2), - insert(Dict, Key, _pipe@3). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 473). --spec do_fold(list({SJ, SK}), SM, fun((SM, SJ, SK) -> SM)) -> SM. -do_fold(List, Initial, Fun) -> - case List of - [] -> - Initial; - - [{K, V} | Rest] -> - do_fold(Rest, Fun(Initial, K, V), Fun) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 505). --spec fold(dict(SN, SO), SR, fun((SR, SN, SO) -> SR)) -> SR. -fold(Dict, Initial, Fun) -> - _pipe = Dict, - _pipe@1 = maps:to_list(_pipe), - do_fold(_pipe@1, Initial, Fun). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 196). --spec map_values(dict(NB, NC), fun((NB, NC) -> NF)) -> dict(NB, NF). -map_values(Dict, Fun) -> - maps:map(Fun, Dict). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 290). --spec filter(dict(OX, OY), fun((OX, OY) -> boolean())) -> dict(OX, OY). -filter(Dict, Predicate) -> - maps:filter(Predicate, Dict). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 537). --spec each(dict(SS, ST), fun((SS, ST) -> any())) -> nil. -each(Dict, Fun) -> - fold( - Dict, - nil, - fun(Nil, K, V) -> - Fun(K, V), - Nil - end - ). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 558). --spec combine(dict(SX, SY), dict(SX, SY), fun((SY, SY) -> SY)) -> dict(SX, SY). -combine(Dict, Other, Fun) -> - fold(Dict, Other, fun(Acc, Key, Value) -> case get(Acc, Key) of - {ok, Other_value} -> - insert(Acc, Key, Fun(Value, Other_value)); - - {error, _} -> - insert(Acc, Key, Value) - end end). diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@dynamic.erl b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@dynamic.erl deleted file mode 100644 index 5d4868e258a..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@dynamic.erl +++ /dev/null @@ -1,832 +0,0 @@ --module(gleam@dynamic). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([from/1, dynamic/1, bit_array/1, classify/1, int/1, float/1, bool/1, shallow_list/1, optional/1, any/1, decode1/2, result/2, list/1, string/1, field/2, optional_field/2, element/2, tuple2/2, tuple3/3, tuple4/4, tuple5/5, tuple6/6, dict/2, decode2/3, decode3/4, decode4/5, decode5/6, decode6/7, decode7/8, decode8/9, decode9/10]). --export_type([dynamic_/0, decode_error/0, unknown_tuple/0]). - --type dynamic_() :: any(). - --type decode_error() :: {decode_error, binary(), binary(), list(binary())}. - --type unknown_tuple() :: any(). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 31). --spec from(any()) -> dynamic_(). -from(A) -> - gleam_stdlib:identity(A). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 39). --spec dynamic(dynamic_()) -> {ok, dynamic_()} | {error, list(decode_error())}. -dynamic(Value) -> - {ok, Value}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 60). --spec bit_array(dynamic_()) -> {ok, bitstring()} | {error, list(decode_error())}. -bit_array(Data) -> - gleam_stdlib:decode_bit_array(Data). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 107). --spec put_expected(decode_error(), binary()) -> decode_error(). -put_expected(Error, Expected) -> - erlang:setelement(2, Error, Expected). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 118). --spec classify(dynamic_()) -> binary(). -classify(Data) -> - gleam_stdlib:classify_dynamic(Data). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 141). --spec int(dynamic_()) -> {ok, integer()} | {error, list(decode_error())}. -int(Data) -> - gleam_stdlib:decode_int(Data). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 164). --spec float(dynamic_()) -> {ok, float()} | {error, list(decode_error())}. -float(Data) -> - gleam_stdlib:decode_float(Data). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 187). --spec bool(dynamic_()) -> {ok, boolean()} | {error, list(decode_error())}. -bool(Data) -> - gleam_stdlib:decode_bool(Data). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 213). --spec shallow_list(dynamic_()) -> {ok, list(dynamic_())} | - {error, list(decode_error())}. -shallow_list(Value) -> - gleam_stdlib:decode_list(Value). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 356). --spec optional(fun((dynamic_()) -> {ok, CJC} | {error, list(decode_error())})) -> fun((dynamic_()) -> {ok, - gleam@option:option(CJC)} | - {error, list(decode_error())}). -optional(Decode) -> - fun(Value) -> gleam_stdlib:decode_option(Value, Decode) end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 491). --spec at_least_decode_tuple_error(integer(), dynamic_()) -> {ok, any()} | - {error, list(decode_error())}. -at_least_decode_tuple_error(Size, Data) -> - S = case Size of - 1 -> - <<""/utf8>>; - - _ -> - <<"s"/utf8>> - end, - Error = begin - _pipe = [<<"Tuple of at least "/utf8>>, - gleam@int:to_string(Size), - <<" element"/utf8>>, - S], - _pipe@1 = gleam@string_builder:from_strings(_pipe), - _pipe@2 = gleam@string_builder:to_string(_pipe@1), - {decode_error, _pipe@2, classify(Data), []} - end, - {error, [Error]}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 1021). --spec any(list(fun((dynamic_()) -> {ok, CNC} | {error, list(decode_error())}))) -> fun((dynamic_()) -> {ok, - CNC} | - {error, list(decode_error())}). -any(Decoders) -> - fun(Data) -> case Decoders of - [] -> - {error, - [{decode_error, <<"another type"/utf8>>, classify(Data), []}]}; - - [Decoder | Decoders@1] -> - case Decoder(Data) of - {ok, Decoded} -> - {ok, Decoded}; - - {error, _} -> - (any(Decoders@1))(Data) - end - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 1517). --spec all_errors({ok, any()} | {error, list(decode_error())}) -> list(decode_error()). -all_errors(Result) -> - case Result of - {ok, _} -> - []; - - {error, Errors} -> - Errors - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 1054). --spec decode1( - fun((CNG) -> CNH), - fun((dynamic_()) -> {ok, CNG} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, CNH} | {error, list(decode_error())}). -decode1(Constructor, T1) -> - fun(Value) -> case T1(Value) of - {ok, A} -> - {ok, Constructor(A)}; - - A@1 -> - {error, all_errors(A@1)} - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 563). --spec push_path(decode_error(), any()) -> decode_error(). -push_path(Error, Name) -> - Name@1 = gleam_stdlib:identity(Name), - Decoder = any( - [fun string/1, - fun(X) -> gleam@result:map(int(X), fun gleam@int:to_string/1) end] - ), - Name@3 = case Decoder(Name@1) of - {ok, Name@2} -> - Name@2; - - {error, _} -> - _pipe = [<<"<"/utf8>>, classify(Name@1), <<">"/utf8>>], - _pipe@1 = gleam@string_builder:from_strings(_pipe), - gleam@string_builder:to_string(_pipe@1) - end, - erlang:setelement(4, Error, [Name@3 | erlang:element(4, Error)]). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 248). --spec result( - fun((dynamic_()) -> {ok, CIQ} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CIS} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, {ok, CIQ} | {error, CIS}} | - {error, list(decode_error())}). -result(Decode_ok, Decode_error) -> - fun(Value) -> - gleam@result:'try'( - gleam_stdlib:decode_result(Value), - fun(Inner_result) -> case Inner_result of - {ok, Raw} -> - gleam@result:'try'( - begin - _pipe = Decode_ok(Raw), - map_errors( - _pipe, - fun(_capture) -> - push_path(_capture, <<"ok"/utf8>>) - end - ) - end, - fun(Value@1) -> {ok, {ok, Value@1}} end - ); - - {error, Raw@1} -> - gleam@result:'try'( - begin - _pipe@1 = Decode_error(Raw@1), - map_errors( - _pipe@1, - fun(_capture@1) -> - push_path(_capture@1, <<"error"/utf8>>) - end - ) - end, - fun(Value@2) -> {ok, {error, Value@2}} end - ) - end end - ) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 301). --spec list(fun((dynamic_()) -> {ok, CIX} | {error, list(decode_error())})) -> fun((dynamic_()) -> {ok, - list(CIX)} | - {error, list(decode_error())}). -list(Decoder_type) -> - fun(Dynamic) -> - gleam@result:'try'(shallow_list(Dynamic), fun(List) -> _pipe = List, - _pipe@1 = gleam@list:try_map(_pipe, Decoder_type), - map_errors( - _pipe@1, - fun(_capture) -> push_path(_capture, <<"*"/utf8>>) end - ) end) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 87). --spec map_errors( - {ok, CHL} | {error, list(decode_error())}, - fun((decode_error()) -> decode_error()) -) -> {ok, CHL} | {error, list(decode_error())}. -map_errors(Result, F) -> - gleam@result:map_error( - Result, - fun(_capture) -> gleam@list:map(_capture, F) end - ). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 95). --spec decode_string(dynamic_()) -> {ok, binary()} | - {error, list(decode_error())}. -decode_string(Data) -> - _pipe = bit_array(Data), - _pipe@1 = map_errors( - _pipe, - fun(_capture) -> put_expected(_capture, <<"String"/utf8>>) end - ), - gleam@result:'try'( - _pipe@1, - fun(Raw) -> case gleam@bit_array:to_string(Raw) of - {ok, String} -> - {ok, String}; - - {error, nil} -> - {error, - [{decode_error, - <<"String"/utf8>>, - <<"BitArray"/utf8>>, - []}]} - end end - ). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 83). --spec string(dynamic_()) -> {ok, binary()} | {error, list(decode_error())}. -string(Data) -> - decode_string(Data). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 385). --spec field( - any(), - fun((dynamic_()) -> {ok, CJM} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, CJM} | {error, list(decode_error())}). -field(Name, Inner_type) -> - fun(Value) -> - Missing_field_error = {decode_error, - <<"field"/utf8>>, - <<"nothing"/utf8>>, - []}, - gleam@result:'try'( - gleam_stdlib:decode_field(Value, Name), - fun(Maybe_inner) -> _pipe = Maybe_inner, - _pipe@1 = gleam@option:to_result(_pipe, [Missing_field_error]), - _pipe@2 = gleam@result:'try'(_pipe@1, Inner_type), - map_errors( - _pipe@2, - fun(_capture) -> push_path(_capture, Name) end - ) end - ) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 427). --spec optional_field( - any(), - fun((dynamic_()) -> {ok, CJQ} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, gleam@option:option(CJQ)} | - {error, list(decode_error())}). -optional_field(Name, Inner_type) -> - fun(Value) -> - gleam@result:'try'( - gleam_stdlib:decode_field(Value, Name), - fun(Maybe_inner) -> case Maybe_inner of - none -> - {ok, none}; - - {some, Dynamic_inner} -> - _pipe = Inner_type(Dynamic_inner), - _pipe@1 = gleam@result:map( - _pipe, - fun(Field@0) -> {some, Field@0} end - ), - map_errors( - _pipe@1, - fun(_capture) -> push_path(_capture, Name) end - ) - end end - ) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 470). --spec element( - integer(), - fun((dynamic_()) -> {ok, CJY} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, CJY} | {error, list(decode_error())}). -element(Index, Inner_type) -> - fun(Data) -> - gleam@result:'try'( - gleam_stdlib:decode_tuple(Data), - fun(Tuple) -> - Size = gleam_stdlib:size_of_tuple(Tuple), - gleam@result:'try'(case Index >= 0 of - true -> - case Index < Size of - true -> - gleam_stdlib:tuple_get(Tuple, Index); - - false -> - at_least_decode_tuple_error(Index + 1, Data) - end; - - false -> - case gleam@int:absolute_value(Index) =< Size of - true -> - gleam_stdlib:tuple_get(Tuple, Size + Index); - - false -> - at_least_decode_tuple_error( - gleam@int:absolute_value(Index), - Data - ) - end - end, fun(Data@1) -> _pipe = Inner_type(Data@1), - map_errors( - _pipe, - fun(_capture) -> push_path(_capture, Index) end - ) end) - end - ) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 553). --spec tuple_errors({ok, any()} | {error, list(decode_error())}, binary()) -> list(decode_error()). -tuple_errors(Result, Name) -> - case Result of - {ok, _} -> - []; - - {error, Errors} -> - gleam@list:map( - Errors, - fun(_capture) -> push_path(_capture, Name) end - ) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 629). --spec tuple2( - fun((dynamic_()) -> {ok, CKY} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CLA} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, {CKY, CLA}} | {error, list(decode_error())}). -tuple2(Decode1, Decode2) -> - fun(Value) -> - gleam@result:'try'( - gleam_stdlib:decode_tuple2(Value), - fun(_use0) -> - {A, B} = _use0, - case {Decode1(A), Decode2(B)} of - {{ok, A@1}, {ok, B@1}} -> - {ok, {A@1, B@1}}; - - {A@2, B@2} -> - _pipe = tuple_errors(A@2, <<"0"/utf8>>), - _pipe@1 = lists:append( - _pipe, - tuple_errors(B@2, <<"1"/utf8>>) - ), - {error, _pipe@1} - end - end - ) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 698). --spec tuple3( - fun((dynamic_()) -> {ok, CLD} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CLF} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CLH} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, {CLD, CLF, CLH}} | {error, list(decode_error())}). -tuple3(Decode1, Decode2, Decode3) -> - fun(Value) -> - gleam@result:'try'( - gleam_stdlib:decode_tuple3(Value), - fun(_use0) -> - {A, B, C} = _use0, - case {Decode1(A), Decode2(B), Decode3(C)} of - {{ok, A@1}, {ok, B@1}, {ok, C@1}} -> - {ok, {A@1, B@1, C@1}}; - - {A@2, B@2, C@2} -> - _pipe = tuple_errors(A@2, <<"0"/utf8>>), - _pipe@1 = lists:append( - _pipe, - tuple_errors(B@2, <<"1"/utf8>>) - ), - _pipe@2 = lists:append( - _pipe@1, - tuple_errors(C@2, <<"2"/utf8>>) - ), - {error, _pipe@2} - end - end - ) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 769). --spec tuple4( - fun((dynamic_()) -> {ok, CLK} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CLM} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CLO} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CLQ} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, {CLK, CLM, CLO, CLQ}} | - {error, list(decode_error())}). -tuple4(Decode1, Decode2, Decode3, Decode4) -> - fun(Value) -> - gleam@result:'try'( - gleam_stdlib:decode_tuple4(Value), - fun(_use0) -> - {A, B, C, D} = _use0, - case {Decode1(A), Decode2(B), Decode3(C), Decode4(D)} of - {{ok, A@1}, {ok, B@1}, {ok, C@1}, {ok, D@1}} -> - {ok, {A@1, B@1, C@1, D@1}}; - - {A@2, B@2, C@2, D@2} -> - _pipe = tuple_errors(A@2, <<"0"/utf8>>), - _pipe@1 = lists:append( - _pipe, - tuple_errors(B@2, <<"1"/utf8>>) - ), - _pipe@2 = lists:append( - _pipe@1, - tuple_errors(C@2, <<"2"/utf8>>) - ), - _pipe@3 = lists:append( - _pipe@2, - tuple_errors(D@2, <<"3"/utf8>>) - ), - {error, _pipe@3} - end - end - ) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 842). --spec tuple5( - fun((dynamic_()) -> {ok, CLT} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CLV} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CLX} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CLZ} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CMB} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, {CLT, CLV, CLX, CLZ, CMB}} | - {error, list(decode_error())}). -tuple5(Decode1, Decode2, Decode3, Decode4, Decode5) -> - fun(Value) -> - gleam@result:'try'( - gleam_stdlib:decode_tuple5(Value), - fun(_use0) -> - {A, B, C, D, E} = _use0, - case {Decode1(A), - Decode2(B), - Decode3(C), - Decode4(D), - Decode5(E)} of - {{ok, A@1}, {ok, B@1}, {ok, C@1}, {ok, D@1}, {ok, E@1}} -> - {ok, {A@1, B@1, C@1, D@1, E@1}}; - - {A@2, B@2, C@2, D@2, E@2} -> - _pipe = tuple_errors(A@2, <<"0"/utf8>>), - _pipe@1 = lists:append( - _pipe, - tuple_errors(B@2, <<"1"/utf8>>) - ), - _pipe@2 = lists:append( - _pipe@1, - tuple_errors(C@2, <<"2"/utf8>>) - ), - _pipe@3 = lists:append( - _pipe@2, - tuple_errors(D@2, <<"3"/utf8>>) - ), - _pipe@4 = lists:append( - _pipe@3, - tuple_errors(E@2, <<"4"/utf8>>) - ), - {error, _pipe@4} - end - end - ) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 917). --spec tuple6( - fun((dynamic_()) -> {ok, CME} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CMG} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CMI} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CMK} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CMM} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CMO} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, {CME, CMG, CMI, CMK, CMM, CMO}} | - {error, list(decode_error())}). -tuple6(Decode1, Decode2, Decode3, Decode4, Decode5, Decode6) -> - fun(Value) -> - gleam@result:'try'( - gleam_stdlib:decode_tuple6(Value), - fun(_use0) -> - {A, B, C, D, E, F} = _use0, - case {Decode1(A), - Decode2(B), - Decode3(C), - Decode4(D), - Decode5(E), - Decode6(F)} of - {{ok, A@1}, - {ok, B@1}, - {ok, C@1}, - {ok, D@1}, - {ok, E@1}, - {ok, F@1}} -> - {ok, {A@1, B@1, C@1, D@1, E@1, F@1}}; - - {A@2, B@2, C@2, D@2, E@2, F@2} -> - _pipe = tuple_errors(A@2, <<"0"/utf8>>), - _pipe@1 = lists:append( - _pipe, - tuple_errors(B@2, <<"1"/utf8>>) - ), - _pipe@2 = lists:append( - _pipe@1, - tuple_errors(C@2, <<"2"/utf8>>) - ), - _pipe@3 = lists:append( - _pipe@2, - tuple_errors(D@2, <<"3"/utf8>>) - ), - _pipe@4 = lists:append( - _pipe@3, - tuple_errors(E@2, <<"4"/utf8>>) - ), - _pipe@5 = lists:append( - _pipe@4, - tuple_errors(F@2, <<"5"/utf8>>) - ), - {error, _pipe@5} - end - end - ) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 968). --spec dict( - fun((dynamic_()) -> {ok, CMR} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CMT} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, gleam@dict:dict(CMR, CMT)} | - {error, list(decode_error())}). -dict(Key_type, Value_type) -> - fun(Value) -> - gleam@result:'try'( - gleam_stdlib:decode_map(Value), - fun(Map) -> - gleam@result:'try'( - begin - _pipe = Map, - _pipe@1 = maps:to_list(_pipe), - gleam@list:try_map( - _pipe@1, - fun(Pair) -> - {K, V} = Pair, - gleam@result:'try'( - begin - _pipe@2 = Key_type(K), - map_errors( - _pipe@2, - fun(_capture) -> - push_path( - _capture, - <<"keys"/utf8>> - ) - end - ) - end, - fun(K@1) -> - gleam@result:'try'( - begin - _pipe@3 = Value_type(V), - map_errors( - _pipe@3, - fun(_capture@1) -> - push_path( - _capture@1, - <<"values"/utf8>> - ) - end - ) - end, - fun(V@1) -> {ok, {K@1, V@1}} end - ) - end - ) - end - ) - end, - fun(Pairs) -> {ok, maps:from_list(Pairs)} end - ) - end - ) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 1082). --spec decode2( - fun((CNK, CNL) -> CNM), - fun((dynamic_()) -> {ok, CNK} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CNL} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, CNM} | {error, list(decode_error())}). -decode2(Constructor, T1, T2) -> - fun(Value) -> case {T1(Value), T2(Value)} of - {{ok, A}, {ok, B}} -> - {ok, Constructor(A, B)}; - - {A@1, B@1} -> - {error, gleam@list:flatten([all_errors(A@1), all_errors(B@1)])} - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 1114). --spec decode3( - fun((CNQ, CNR, CNS) -> CNT), - fun((dynamic_()) -> {ok, CNQ} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CNR} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CNS} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, CNT} | {error, list(decode_error())}). -decode3(Constructor, T1, T2, T3) -> - fun(Value) -> case {T1(Value), T2(Value), T3(Value)} of - {{ok, A}, {ok, B}, {ok, C}} -> - {ok, Constructor(A, B, C)}; - - {A@1, B@1, C@1} -> - {error, - gleam@list:flatten( - [all_errors(A@1), all_errors(B@1), all_errors(C@1)] - )} - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 1160). --spec decode4( - fun((CNY, CNZ, COA, COB) -> COC), - fun((dynamic_()) -> {ok, CNY} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CNZ} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, COA} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, COB} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, COC} | {error, list(decode_error())}). -decode4(Constructor, T1, T2, T3, T4) -> - fun(X) -> case {T1(X), T2(X), T3(X), T4(X)} of - {{ok, A}, {ok, B}, {ok, C}, {ok, D}} -> - {ok, Constructor(A, B, C, D)}; - - {A@1, B@1, C@1, D@1} -> - {error, - gleam@list:flatten( - [all_errors(A@1), - all_errors(B@1), - all_errors(C@1), - all_errors(D@1)] - )} - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 1216). --spec decode5( - fun((COI, COJ, COK, COL, COM) -> CON), - fun((dynamic_()) -> {ok, COI} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, COJ} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, COK} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, COL} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, COM} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, CON} | {error, list(decode_error())}). -decode5(Constructor, T1, T2, T3, T4, T5) -> - fun(X) -> case {T1(X), T2(X), T3(X), T4(X), T5(X)} of - {{ok, A}, {ok, B}, {ok, C}, {ok, D}, {ok, E}} -> - {ok, Constructor(A, B, C, D, E)}; - - {A@1, B@1, C@1, D@1, E@1} -> - {error, - gleam@list:flatten( - [all_errors(A@1), - all_errors(B@1), - all_errors(C@1), - all_errors(D@1), - all_errors(E@1)] - )} - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 1276). --spec decode6( - fun((COU, COV, COW, COX, COY, COZ) -> CPA), - fun((dynamic_()) -> {ok, COU} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, COV} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, COW} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, COX} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, COY} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, COZ} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, CPA} | {error, list(decode_error())}). -decode6(Constructor, T1, T2, T3, T4, T5, T6) -> - fun(X) -> case {T1(X), T2(X), T3(X), T4(X), T5(X), T6(X)} of - {{ok, A}, {ok, B}, {ok, C}, {ok, D}, {ok, E}, {ok, F}} -> - {ok, Constructor(A, B, C, D, E, F)}; - - {A@1, B@1, C@1, D@1, E@1, F@1} -> - {error, - gleam@list:flatten( - [all_errors(A@1), - all_errors(B@1), - all_errors(C@1), - all_errors(D@1), - all_errors(E@1), - all_errors(F@1)] - )} - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 1341). --spec decode7( - fun((CPI, CPJ, CPK, CPL, CPM, CPN, CPO) -> CPP), - fun((dynamic_()) -> {ok, CPI} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CPJ} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CPK} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CPL} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CPM} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CPN} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CPO} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, CPP} | {error, list(decode_error())}). -decode7(Constructor, T1, T2, T3, T4, T5, T6, T7) -> - fun(X) -> case {T1(X), T2(X), T3(X), T4(X), T5(X), T6(X), T7(X)} of - {{ok, A}, {ok, B}, {ok, C}, {ok, D}, {ok, E}, {ok, F}, {ok, G}} -> - {ok, Constructor(A, B, C, D, E, F, G)}; - - {A@1, B@1, C@1, D@1, E@1, F@1, G@1} -> - {error, - gleam@list:flatten( - [all_errors(A@1), - all_errors(B@1), - all_errors(C@1), - all_errors(D@1), - all_errors(E@1), - all_errors(F@1), - all_errors(G@1)] - )} - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 1410). --spec decode8( - fun((CPY, CPZ, CQA, CQB, CQC, CQD, CQE, CQF) -> CQG), - fun((dynamic_()) -> {ok, CPY} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CPZ} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQA} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQB} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQC} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQD} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQE} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQF} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, CQG} | {error, list(decode_error())}). -decode8(Constructor, T1, T2, T3, T4, T5, T6, T7, T8) -> - fun(X) -> case {T1(X), T2(X), T3(X), T4(X), T5(X), T6(X), T7(X), T8(X)} of - {{ok, A}, - {ok, B}, - {ok, C}, - {ok, D}, - {ok, E}, - {ok, F}, - {ok, G}, - {ok, H}} -> - {ok, Constructor(A, B, C, D, E, F, G, H)}; - - {A@1, B@1, C@1, D@1, E@1, F@1, G@1, H@1} -> - {error, - gleam@list:flatten( - [all_errors(A@1), - all_errors(B@1), - all_errors(C@1), - all_errors(D@1), - all_errors(E@1), - all_errors(F@1), - all_errors(G@1), - all_errors(H@1)] - )} - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 1483). --spec decode9( - fun((CQQ, CQR, CQS, CQT, CQU, CQV, CQW, CQX, CQY) -> CQZ), - fun((dynamic_()) -> {ok, CQQ} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQR} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQS} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQT} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQU} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQV} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQW} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQX} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQY} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, CQZ} | {error, list(decode_error())}). -decode9(Constructor, T1, T2, T3, T4, T5, T6, T7, T8, T9) -> - fun(X) -> - case {T1(X), T2(X), T3(X), T4(X), T5(X), T6(X), T7(X), T8(X), T9(X)} of - {{ok, A}, - {ok, B}, - {ok, C}, - {ok, D}, - {ok, E}, - {ok, F}, - {ok, G}, - {ok, H}, - {ok, I}} -> - {ok, Constructor(A, B, C, D, E, F, G, H, I)}; - - {A@1, B@1, C@1, D@1, E@1, F@1, G@1, H@1, I@1} -> - {error, - gleam@list:flatten( - [all_errors(A@1), - all_errors(B@1), - all_errors(C@1), - all_errors(D@1), - all_errors(E@1), - all_errors(F@1), - all_errors(G@1), - all_errors(H@1), - all_errors(I@1)] - )} - end - end. diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@float.erl b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@float.erl deleted file mode 100644 index 99936162837..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@float.erl +++ /dev/null @@ -1,231 +0,0 @@ --module(gleam@float). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([parse/1, to_string/1, compare/2, min/2, max/2, clamp/3, ceiling/1, floor/1, truncate/1, absolute_value/1, loosely_compare/3, loosely_equals/3, power/2, square_root/1, negate/1, round/1, to_precision/2, sum/1, product/1, random/0, modulo/2, divide/2, add/2, multiply/2, subtract/2]). - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 32). --spec parse(binary()) -> {ok, float()} | {error, nil}. -parse(String) -> - gleam_stdlib:parse_float(String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 49). --spec to_string(float()) -> binary(). -to_string(X) -> - gleam_stdlib:float_to_string(X). - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 86). --spec compare(float(), float()) -> gleam@order:order(). -compare(A, B) -> - case A =:= B of - true -> - eq; - - false -> - case A < B of - true -> - lt; - - false -> - gt - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 167). --spec min(float(), float()) -> float(). -min(A, B) -> - case A < B of - true -> - A; - - false -> - B - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 183). --spec max(float(), float()) -> float(). -max(A, B) -> - case A > B of - true -> - A; - - false -> - B - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 66). --spec clamp(float(), float(), float()) -> float(). -clamp(X, Min_bound, Max_bound) -> - _pipe = X, - _pipe@1 = min(_pipe, Max_bound), - max(_pipe@1, Min_bound). - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 199). --spec ceiling(float()) -> float(). -ceiling(X) -> - math:ceil(X). - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 216). --spec floor(float()) -> float(). -floor(X) -> - math:floor(X). - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 262). --spec truncate(float()) -> integer(). -truncate(X) -> - erlang:trunc(X). - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 310). --spec absolute_value(float()) -> float(). -absolute_value(X) -> - case X >= +0.0 of - true -> - X; - - _ -> - +0.0 - X - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 116). --spec loosely_compare(float(), float(), float()) -> gleam@order:order(). -loosely_compare(A, B, Tolerance) -> - Difference = absolute_value(A - B), - case Difference =< Tolerance of - true -> - eq; - - false -> - compare(A, B) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 149). --spec loosely_equals(float(), float(), float()) -> boolean(). -loosely_equals(A, B, Tolerance) -> - Difference = absolute_value(A - B), - Difference =< Tolerance. - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 347). --spec power(float(), float()) -> {ok, float()} | {error, nil}. -power(Base, Exponent) -> - Fractional = (ceiling(Exponent) - Exponent) > +0.0, - case ((Base < +0.0) andalso Fractional) orelse ((Base =:= +0.0) andalso (Exponent - < +0.0)) of - true -> - {error, nil}; - - false -> - {ok, math:pow(Base, Exponent)} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 379). --spec square_root(float()) -> {ok, float()} | {error, nil}. -square_root(X) -> - power(X, 0.5). - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 392). --spec negate(float()) -> float(). -negate(X) -> - -1.0 * X. - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 238). --spec round(float()) -> integer(). -round(X) -> - erlang:round(X). - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 287). --spec to_precision(float(), integer()) -> float(). -to_precision(X, Precision) -> - Factor = math:pow(10.0, erlang:float(- Precision)), - erlang:float(round(case Factor of - +0.0 -> +0.0; - -0.0 -> -0.0; - Gleam@denominator -> X / Gleam@denominator - end)) * Factor. - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 410). --spec do_sum(list(float()), float()) -> float(). -do_sum(Numbers, Initial) -> - case Numbers of - [] -> - Initial; - - [X | Rest] -> - do_sum(Rest, X + Initial) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 405). --spec sum(list(float())) -> float(). -sum(Numbers) -> - _pipe = Numbers, - do_sum(_pipe, +0.0). - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 433). --spec do_product(list(float()), float()) -> float(). -do_product(Numbers, Initial) -> - case Numbers of - [] -> - Initial; - - [X | Rest] -> - do_product(Rest, X * Initial) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 426). --spec product(list(float())) -> float(). -product(Numbers) -> - case Numbers of - [] -> - 1.0; - - _ -> - do_product(Numbers, 1.0) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 455). --spec random() -> float(). -random() -> - rand:uniform(). - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 484). --spec modulo(float(), float()) -> {ok, float()} | {error, nil}. -modulo(Dividend, Divisor) -> - case Divisor of - +0.0 -> - {error, nil}; - - _ -> - {ok, Dividend - (floor(case Divisor of - +0.0 -> +0.0; - -0.0 -> -0.0; - Gleam@denominator -> Dividend / Gleam@denominator - end) * Divisor)} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 505). --spec divide(float(), float()) -> {ok, float()} | {error, nil}. -divide(A, B) -> - case B of - +0.0 -> - {error, nil}; - - B@1 -> - {ok, case B@1 of - +0.0 -> +0.0; - -0.0 -> -0.0; - Gleam@denominator -> A / Gleam@denominator - end} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 536). --spec add(float(), float()) -> float(). -add(A, B) -> - A + B. - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 564). --spec multiply(float(), float()) -> float(). -multiply(A, B) -> - A * B. - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 597). --spec subtract(float(), float()) -> float(). -subtract(A, B) -> - A - B. diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@function.erl b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@function.erl deleted file mode 100644 index e3895743459..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@function.erl +++ /dev/null @@ -1,80 +0,0 @@ --module(gleam@function). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([compose/2, curry2/1, curry3/1, curry4/1, curry5/1, curry6/1, flip/1, identity/1, constant/1, tap/2, apply1/2, apply2/3, apply3/4]). - --file("/Users/louis/src/gleam/stdlib/src/gleam/function.gleam", 2). --spec compose(fun((DPR) -> DPS), fun((DPS) -> DPT)) -> fun((DPR) -> DPT). -compose(Fun1, Fun2) -> - fun(A) -> Fun2(Fun1(A)) end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/function.gleam", 7). --spec curry2(fun((DPU, DPV) -> DPW)) -> fun((DPU) -> fun((DPV) -> DPW)). -curry2(Fun) -> - fun(A) -> fun(B) -> Fun(A, B) end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/function.gleam", 12). --spec curry3(fun((DPY, DPZ, DQA) -> DQB)) -> fun((DPY) -> fun((DPZ) -> fun((DQA) -> DQB))). -curry3(Fun) -> - fun(A) -> fun(B) -> fun(C) -> Fun(A, B, C) end end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/function.gleam", 17). --spec curry4(fun((DQD, DQE, DQF, DQG) -> DQH)) -> fun((DQD) -> fun((DQE) -> fun((DQF) -> fun((DQG) -> DQH)))). -curry4(Fun) -> - fun(A) -> fun(B) -> fun(C) -> fun(D) -> Fun(A, B, C, D) end end end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/function.gleam", 22). --spec curry5(fun((DQJ, DQK, DQL, DQM, DQN) -> DQO)) -> fun((DQJ) -> fun((DQK) -> fun((DQL) -> fun((DQM) -> fun((DQN) -> DQO))))). -curry5(Fun) -> - fun(A) -> - fun(B) -> - fun(C) -> fun(D) -> fun(E) -> Fun(A, B, C, D, E) end end end - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/function.gleam", 27). --spec curry6(fun((DQQ, DQR, DQS, DQT, DQU, DQV) -> DQW)) -> fun((DQQ) -> fun((DQR) -> fun((DQS) -> fun((DQT) -> fun((DQU) -> fun((DQV) -> DQW)))))). -curry6(Fun) -> - fun(A) -> - fun(B) -> - fun(C) -> - fun(D) -> fun(E) -> fun(F) -> Fun(A, B, C, D, E, F) end end end - end - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/function.gleam", 36). --spec flip(fun((DQY, DQZ) -> DRA)) -> fun((DQZ, DQY) -> DRA). -flip(Fun) -> - fun(B, A) -> Fun(A, B) end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/function.gleam", 42). --spec identity(DRB) -> DRB. -identity(X) -> - X. - --file("/Users/louis/src/gleam/stdlib/src/gleam/function.gleam", 47). --spec constant(DRC) -> fun((any()) -> DRC). -constant(Value) -> - fun(_) -> Value end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/function.gleam", 56). --spec tap(DRE, fun((DRE) -> any())) -> DRE. -tap(Arg, Effect) -> - Effect(Arg), - Arg. - --file("/Users/louis/src/gleam/stdlib/src/gleam/function.gleam", 62). --spec apply1(fun((DRG) -> DRH), DRG) -> DRH. -apply1(Fun, Arg1) -> - Fun(Arg1). - --file("/Users/louis/src/gleam/stdlib/src/gleam/function.gleam", 67). --spec apply2(fun((DRI, DRJ) -> DRK), DRI, DRJ) -> DRK. -apply2(Fun, Arg1, Arg2) -> - Fun(Arg1, Arg2). - --file("/Users/louis/src/gleam/stdlib/src/gleam/function.gleam", 72). --spec apply3(fun((DRL, DRM, DRN) -> DRO), DRL, DRM, DRN) -> DRO. -apply3(Fun, Arg1, Arg2, Arg3) -> - Fun(Arg1, Arg2, Arg3). diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@int.erl b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@int.erl deleted file mode 100644 index c1ca0dabbb7..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@int.erl +++ /dev/null @@ -1,367 +0,0 @@ --module(gleam@int). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([absolute_value/1, parse/1, base_parse/2, to_string/1, to_base_string/2, to_base2/1, to_base8/1, to_base16/1, to_base36/1, to_float/1, power/2, square_root/1, compare/2, min/2, max/2, clamp/3, is_even/1, is_odd/1, negate/1, sum/1, product/1, digits/2, undigits/2, random/1, divide/2, remainder/2, modulo/2, floor_divide/2, add/2, multiply/2, subtract/2, bitwise_and/2, bitwise_not/1, bitwise_or/2, bitwise_exclusive_or/2, bitwise_shift_left/2, bitwise_shift_right/2]). - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 30). --spec absolute_value(integer()) -> integer(). -absolute_value(X) -> - case X >= 0 of - true -> - X; - - false -> - X * -1 - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 107). --spec parse(binary()) -> {ok, integer()} | {error, nil}. -parse(String) -> - gleam_stdlib:parse_int(String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 145). --spec base_parse(binary(), integer()) -> {ok, integer()} | {error, nil}. -base_parse(String, Base) -> - case (Base >= 2) andalso (Base =< 36) of - true -> - gleam_stdlib:int_from_base_string(String, Base); - - false -> - {error, nil} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 165). --spec to_string(integer()) -> binary(). -to_string(X) -> - erlang:integer_to_binary(X). - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 204). --spec to_base_string(integer(), integer()) -> {ok, binary()} | {error, nil}. -to_base_string(X, Base) -> - case (Base >= 2) andalso (Base =< 36) of - true -> - {ok, erlang:integer_to_binary(X, Base)}; - - false -> - {error, nil} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 224). --spec to_base2(integer()) -> binary(). -to_base2(X) -> - erlang:integer_to_binary(X, 2). - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 237). --spec to_base8(integer()) -> binary(). -to_base8(X) -> - erlang:integer_to_binary(X, 8). - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 250). --spec to_base16(integer()) -> binary(). -to_base16(X) -> - erlang:integer_to_binary(X, 16). - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 263). --spec to_base36(integer()) -> binary(). -to_base36(X) -> - erlang:integer_to_binary(X, 36). - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 286). --spec to_float(integer()) -> float(). -to_float(X) -> - erlang:float(X). - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 67). --spec power(integer(), float()) -> {ok, float()} | {error, nil}. -power(Base, Exponent) -> - _pipe = Base, - _pipe@1 = to_float(_pipe), - gleam@float:power(_pipe@1, Exponent). - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 87). --spec square_root(integer()) -> {ok, float()} | {error, nil}. -square_root(X) -> - _pipe = X, - _pipe@1 = to_float(_pipe), - gleam@float:square_root(_pipe@1). - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 328). --spec compare(integer(), integer()) -> gleam@order:order(). -compare(A, B) -> - case A =:= B of - true -> - eq; - - false -> - case A < B of - true -> - lt; - - false -> - gt - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 348). --spec min(integer(), integer()) -> integer(). -min(A, B) -> - case A < B of - true -> - A; - - false -> - B - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 364). --spec max(integer(), integer()) -> integer(). -max(A, B) -> - case A > B of - true -> - A; - - false -> - B - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 303). --spec clamp(integer(), integer(), integer()) -> integer(). -clamp(X, Min_bound, Max_bound) -> - _pipe = X, - _pipe@1 = min(_pipe, Max_bound), - max(_pipe@1, Min_bound). - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 385). --spec is_even(integer()) -> boolean(). -is_even(X) -> - (X rem 2) =:= 0. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 403). --spec is_odd(integer()) -> boolean(). -is_odd(X) -> - (X rem 2) /= 0. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 416). --spec negate(integer()) -> integer(). -negate(X) -> - -1 * X. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 434). --spec do_sum(list(integer()), integer()) -> integer(). -do_sum(Numbers, Initial) -> - case Numbers of - [] -> - Initial; - - [X | Rest] -> - do_sum(Rest, X + Initial) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 429). --spec sum(list(integer())) -> integer(). -sum(Numbers) -> - _pipe = Numbers, - do_sum(_pipe, 0). - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 457). --spec do_product(list(integer()), integer()) -> integer(). -do_product(Numbers, Initial) -> - case Numbers of - [] -> - Initial; - - [X | Rest] -> - do_product(Rest, X * Initial) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 450). --spec product(list(integer())) -> integer(). -product(Numbers) -> - case Numbers of - [] -> - 1; - - _ -> - do_product(Numbers, 1) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 486). --spec do_digits(integer(), integer(), list(integer())) -> list(integer()). -do_digits(X, Base, Acc) -> - case absolute_value(X) < Base of - true -> - [X | Acc]; - - false -> - do_digits(case Base of - 0 -> 0; - Gleam@denominator -> X div Gleam@denominator - end, Base, [case Base of - 0 -> 0; - Gleam@denominator@1 -> X rem Gleam@denominator@1 - end | Acc]) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 479). --spec digits(integer(), integer()) -> {ok, list(integer())} | {error, nil}. -digits(X, Base) -> - case Base < 2 of - true -> - {error, nil}; - - false -> - {ok, do_digits(X, Base, [])} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 520). --spec do_undigits(list(integer()), integer(), integer()) -> {ok, integer()} | - {error, nil}. -do_undigits(Numbers, Base, Acc) -> - case Numbers of - [] -> - {ok, Acc}; - - [Digit | _] when Digit >= Base -> - {error, nil}; - - [Digit@1 | Rest] -> - do_undigits(Rest, Base, (Acc * Base) + Digit@1) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 513). --spec undigits(list(integer()), integer()) -> {ok, integer()} | {error, nil}. -undigits(Numbers, Base) -> - case Base < 2 of - true -> - {error, nil}; - - false -> - do_undigits(Numbers, Base, 0) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 549). --spec random(integer()) -> integer(). -random(Max) -> - _pipe = (rand:uniform() * to_float(Max)), - _pipe@1 = gleam@float:floor(_pipe), - gleam@float:round(_pipe@1). - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 582). --spec divide(integer(), integer()) -> {ok, integer()} | {error, nil}. -divide(Dividend, Divisor) -> - case Divisor of - 0 -> - {error, nil}; - - Divisor@1 -> - {ok, case Divisor@1 of - 0 -> 0; - Gleam@denominator -> Dividend div Gleam@denominator - end} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 634). --spec remainder(integer(), integer()) -> {ok, integer()} | {error, nil}. -remainder(Dividend, Divisor) -> - case Divisor of - 0 -> - {error, nil}; - - Divisor@1 -> - {ok, case Divisor@1 of - 0 -> 0; - Gleam@denominator -> Dividend rem Gleam@denominator - end} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 676). --spec modulo(integer(), integer()) -> {ok, integer()} | {error, nil}. -modulo(Dividend, Divisor) -> - case Divisor of - 0 -> - {error, nil}; - - _ -> - Remainder = case Divisor of - 0 -> 0; - Gleam@denominator -> Dividend rem Gleam@denominator - end, - case (Remainder * Divisor) < 0 of - true -> - {ok, Remainder + Divisor}; - - false -> - {ok, Remainder} - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 720). --spec floor_divide(integer(), integer()) -> {ok, integer()} | {error, nil}. -floor_divide(Dividend, Divisor) -> - case Divisor of - 0 -> - {error, nil}; - - Divisor@1 -> - case ((Dividend * Divisor@1) < 0) andalso ((case Divisor@1 of - 0 -> 0; - Gleam@denominator -> Dividend rem Gleam@denominator - end) /= 0) of - true -> - {ok, (case Divisor@1 of - 0 -> 0; - Gleam@denominator@1 -> Dividend div Gleam@denominator@1 - end) - 1}; - - false -> - {ok, case Divisor@1 of - 0 -> 0; - Gleam@denominator@2 -> Dividend div Gleam@denominator@2 - end} - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 754). --spec add(integer(), integer()) -> integer(). -add(A, B) -> - A + B. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 782). --spec multiply(integer(), integer()) -> integer(). -multiply(A, B) -> - A * B. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 815). --spec subtract(integer(), integer()) -> integer(). -subtract(A, B) -> - A - B. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 827). --spec bitwise_and(integer(), integer()) -> integer(). -bitwise_and(X, Y) -> - erlang:'band'(X, Y). - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 837). --spec bitwise_not(integer()) -> integer(). -bitwise_not(X) -> - erlang:'bnot'(X). - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 847). --spec bitwise_or(integer(), integer()) -> integer(). -bitwise_or(X, Y) -> - erlang:'bor'(X, Y). - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 857). --spec bitwise_exclusive_or(integer(), integer()) -> integer(). -bitwise_exclusive_or(X, Y) -> - erlang:'bxor'(X, Y). - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 867). --spec bitwise_shift_left(integer(), integer()) -> integer(). -bitwise_shift_left(X, Y) -> - erlang:'bsl'(X, Y). - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 877). --spec bitwise_shift_right(integer(), integer()) -> integer(). -bitwise_shift_right(X, Y) -> - erlang:'bsr'(X, Y). diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@io.erl b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@io.erl deleted file mode 100644 index 43ca590a484..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@io.erl +++ /dev/null @@ -1,32 +0,0 @@ --module(gleam@io). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([print/1, print_error/1, println/1, println_error/1, debug/1]). - --file("/Users/louis/src/gleam/stdlib/src/gleam/io.gleam", 15). --spec print(binary()) -> nil. -print(String) -> - gleam_stdlib:print(String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/io.gleam", 35). --spec print_error(binary()) -> nil. -print_error(String) -> - gleam_stdlib:print_error(String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/io.gleam", 53). --spec println(binary()) -> nil. -println(String) -> - gleam_stdlib:println(String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/io.gleam", 71). --spec println_error(binary()) -> nil. -println_error(String) -> - gleam_stdlib:println_error(String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/io.gleam", 108). --spec debug(DSO) -> DSO. -debug(Term) -> - _pipe = Term, - _pipe@1 = gleam@string:inspect(_pipe), - gleam_stdlib:println_error(_pipe@1), - Term. diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@iterator.erl b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@iterator.erl deleted file mode 100644 index e903db771c3..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@iterator.erl +++ /dev/null @@ -1,873 +0,0 @@ --module(gleam@iterator). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([unfold/2, repeatedly/1, repeat/1, from_list/1, transform/3, fold/3, run/1, to_list/1, step/1, take/2, drop/2, map/2, map2/3, append/2, flatten/1, concat/1, flat_map/2, filter/2, filter_map/2, cycle/1, find/2, find_map/2, index/1, iterate/2, take_while/2, drop_while/2, scan/3, zip/2, chunk/2, sized_chunk/2, intersperse/2, any/2, all/2, group/2, reduce/2, last/1, empty/0, once/1, range/2, single/1, interleave/2, fold_until/3, try_fold/3, first/1, at/2, length/1, each/2, yield/2]). --export_type([action/1, iterator/1, step/2, chunk/2, sized_chunk/1]). - --type action(DSY) :: stop | {continue, DSY, fun(() -> action(DSY))}. - --opaque iterator(DSZ) :: {iterator, fun(() -> action(DSZ))}. - --type step(DTA, DTB) :: {next, DTA, DTB} | done. - --type chunk(DTC, DTD) :: {another_by, - list(DTC), - DTD, - DTC, - fun(() -> action(DTC))} | - {last_by, list(DTC)}. - --type sized_chunk(DTE) :: {another, list(DTE), fun(() -> action(DTE))} | - {last, list(DTE)} | - no_more. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 37). --spec stop() -> action(any()). -stop() -> - stop. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 42). --spec do_unfold(DTH, fun((DTH) -> step(DTI, DTH))) -> fun(() -> action(DTI)). -do_unfold(Initial, F) -> - fun() -> case F(Initial) of - {next, X, Acc} -> - {continue, X, do_unfold(Acc, F)}; - - done -> - stop - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 75). --spec unfold(DTM, fun((DTM) -> step(DTN, DTM))) -> iterator(DTN). -unfold(Initial, F) -> - _pipe = Initial, - _pipe@1 = do_unfold(_pipe, F), - {iterator, _pipe@1}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 94). --spec repeatedly(fun(() -> DTR)) -> iterator(DTR). -repeatedly(F) -> - unfold(nil, fun(_) -> {next, F(), nil} end). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 109). --spec repeat(DTT) -> iterator(DTT). -repeat(X) -> - repeatedly(fun() -> X end). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 123). --spec from_list(list(DTV)) -> iterator(DTV). -from_list(List) -> - Yield = fun(Acc) -> case Acc of - [] -> - done; - - [Head | Tail] -> - {next, Head, Tail} - end end, - unfold(List, Yield). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 134). --spec do_transform( - fun(() -> action(DTY)), - DUA, - fun((DUA, DTY) -> step(DUB, DUA)) -) -> fun(() -> action(DUB)). -do_transform(Continuation, State, F) -> - fun() -> case Continuation() of - stop -> - stop; - - {continue, El, Next} -> - case F(State, El) of - done -> - stop; - - {next, Yield, Next_state} -> - {continue, Yield, do_transform(Next, Next_state, F)} - end - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 169). --spec transform(iterator(DUF), DUH, fun((DUH, DUF) -> step(DUI, DUH))) -> iterator(DUI). -transform(Iterator, Initial, F) -> - _pipe = do_transform(erlang:element(2, Iterator), Initial, F), - {iterator, _pipe}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 178). --spec do_fold(fun(() -> action(DUM)), fun((DUO, DUM) -> DUO), DUO) -> DUO. -do_fold(Continuation, F, Accumulator) -> - case Continuation() of - {continue, Elem, Next} -> - do_fold(Next, F, F(Accumulator, Elem)); - - stop -> - Accumulator - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 206). --spec fold(iterator(DUP), DUR, fun((DUR, DUP) -> DUR)) -> DUR. -fold(Iterator, Initial, F) -> - _pipe = erlang:element(2, Iterator), - do_fold(_pipe, F, Initial). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 220). --spec run(iterator(any())) -> nil. -run(Iterator) -> - fold(Iterator, nil, fun(_, _) -> nil end). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 238). --spec to_list(iterator(DUU)) -> list(DUU). -to_list(Iterator) -> - _pipe = Iterator, - _pipe@1 = fold(_pipe, [], fun(Acc, E) -> [E | Acc] end), - lists:reverse(_pipe@1). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 266). --spec step(iterator(DUX)) -> step(DUX, iterator(DUX)). -step(Iterator) -> - case (erlang:element(2, Iterator))() of - stop -> - done; - - {continue, E, A} -> - {next, E, {iterator, A}} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 273). --spec do_take(fun(() -> action(DVC)), integer()) -> fun(() -> action(DVC)). -do_take(Continuation, Desired) -> - fun() -> case Desired > 0 of - false -> - stop; - - true -> - case Continuation() of - stop -> - stop; - - {continue, E, Next} -> - {continue, E, do_take(Next, Desired - 1)} - end - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 306). --spec take(iterator(DVF), integer()) -> iterator(DVF). -take(Iterator, Desired) -> - _pipe = erlang:element(2, Iterator), - _pipe@1 = do_take(_pipe, Desired), - {iterator, _pipe@1}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 312). --spec do_drop(fun(() -> action(DVI)), integer()) -> action(DVI). -do_drop(Continuation, Desired) -> - case Continuation() of - stop -> - stop; - - {continue, E, Next} -> - case Desired > 0 of - true -> - do_drop(Next, Desired - 1); - - false -> - {continue, E, Next} - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 348). --spec drop(iterator(DVL), integer()) -> iterator(DVL). -drop(Iterator, Desired) -> - _pipe = fun() -> do_drop(erlang:element(2, Iterator), Desired) end, - {iterator, _pipe}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 353). --spec do_map(fun(() -> action(DVO)), fun((DVO) -> DVQ)) -> fun(() -> action(DVQ)). -do_map(Continuation, F) -> - fun() -> case Continuation() of - stop -> - stop; - - {continue, E, Continuation@1} -> - {continue, F(E), do_map(Continuation@1, F)} - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 379). --spec map(iterator(DVS), fun((DVS) -> DVU)) -> iterator(DVU). -map(Iterator, F) -> - _pipe = erlang:element(2, Iterator), - _pipe@1 = do_map(_pipe, F), - {iterator, _pipe@1}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 385). --spec do_map2( - fun(() -> action(DVW)), - fun(() -> action(DVY)), - fun((DVW, DVY) -> DWA) -) -> fun(() -> action(DWA)). -do_map2(Continuation1, Continuation2, Fun) -> - fun() -> case Continuation1() of - stop -> - stop; - - {continue, A, Next_a} -> - case Continuation2() of - stop -> - stop; - - {continue, B, Next_b} -> - {continue, Fun(A, B), do_map2(Next_a, Next_b, Fun)} - end - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 426). --spec map2(iterator(DWC), iterator(DWE), fun((DWC, DWE) -> DWG)) -> iterator(DWG). -map2(Iterator1, Iterator2, Fun) -> - _pipe = do_map2( - erlang:element(2, Iterator1), - erlang:element(2, Iterator2), - Fun - ), - {iterator, _pipe}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 435). --spec do_append(fun(() -> action(DWI)), fun(() -> action(DWI))) -> action(DWI). -do_append(First, Second) -> - case First() of - {continue, E, First@1} -> - {continue, E, fun() -> do_append(First@1, Second) end}; - - stop -> - Second() - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 456). --spec append(iterator(DWM), iterator(DWM)) -> iterator(DWM). -append(First, Second) -> - _pipe = fun() -> - do_append(erlang:element(2, First), erlang:element(2, Second)) - end, - {iterator, _pipe}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 461). --spec do_flatten(fun(() -> action(iterator(DWQ)))) -> action(DWQ). -do_flatten(Flattened) -> - case Flattened() of - stop -> - stop; - - {continue, It, Next_iterator} -> - do_append( - erlang:element(2, It), - fun() -> do_flatten(Next_iterator) end - ) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 484). --spec flatten(iterator(iterator(DWU))) -> iterator(DWU). -flatten(Iterator) -> - _pipe = fun() -> do_flatten(erlang:element(2, Iterator)) end, - {iterator, _pipe}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 504). --spec concat(list(iterator(DWY))) -> iterator(DWY). -concat(Iterators) -> - flatten(from_list(Iterators)). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 526). --spec flat_map(iterator(DXC), fun((DXC) -> iterator(DXE))) -> iterator(DXE). -flat_map(Iterator, F) -> - _pipe = Iterator, - _pipe@1 = map(_pipe, F), - flatten(_pipe@1). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 535). --spec do_filter(fun(() -> action(DXH)), fun((DXH) -> boolean())) -> action(DXH). -do_filter(Continuation, Predicate) -> - case Continuation() of - stop -> - stop; - - {continue, E, Iterator} -> - case Predicate(E) of - true -> - {continue, E, fun() -> do_filter(Iterator, Predicate) end}; - - false -> - do_filter(Iterator, Predicate) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 568). --spec filter(iterator(DXK), fun((DXK) -> boolean())) -> iterator(DXK). -filter(Iterator, Predicate) -> - _pipe = fun() -> do_filter(erlang:element(2, Iterator), Predicate) end, - {iterator, _pipe}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 576). --spec do_filter_map( - fun(() -> action(DXN)), - fun((DXN) -> {ok, DXP} | {error, any()}) -) -> action(DXP). -do_filter_map(Continuation, F) -> - case Continuation() of - stop -> - stop; - - {continue, E, Next} -> - case F(E) of - {ok, E@1} -> - {continue, E@1, fun() -> do_filter_map(Next, F) end}; - - {error, _} -> - do_filter_map(Next, F) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 612). --spec filter_map(iterator(DXU), fun((DXU) -> {ok, DXW} | {error, any()})) -> iterator(DXW). -filter_map(Iterator, F) -> - _pipe = fun() -> do_filter_map(erlang:element(2, Iterator), F) end, - {iterator, _pipe}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 632). --spec cycle(iterator(DYB)) -> iterator(DYB). -cycle(Iterator) -> - _pipe = repeat(Iterator), - flatten(_pipe). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 678). --spec do_find(fun(() -> action(DYF)), fun((DYF) -> boolean())) -> {ok, DYF} | - {error, nil}. -do_find(Continuation, F) -> - case Continuation() of - stop -> - {error, nil}; - - {continue, E, Next} -> - case F(E) of - true -> - {ok, E}; - - false -> - do_find(Next, F) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 712). --spec find(iterator(DYJ), fun((DYJ) -> boolean())) -> {ok, DYJ} | {error, nil}. -find(Haystack, Is_desired) -> - _pipe = erlang:element(2, Haystack), - do_find(_pipe, Is_desired). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 720). --spec do_find_map( - fun(() -> action(DYN)), - fun((DYN) -> {ok, DYP} | {error, any()}) -) -> {ok, DYP} | {error, nil}. -do_find_map(Continuation, F) -> - case Continuation() of - stop -> - {error, nil}; - - {continue, E, Next} -> - case F(E) of - {ok, E@1} -> - {ok, E@1}; - - {error, _} -> - do_find_map(Next, F) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 757). --spec find_map(iterator(DYV), fun((DYV) -> {ok, DYX} | {error, any()})) -> {ok, - DYX} | - {error, nil}. -find_map(Haystack, Is_desired) -> - _pipe = erlang:element(2, Haystack), - do_find_map(_pipe, Is_desired). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 765). --spec do_index(fun(() -> action(DZD)), integer()) -> fun(() -> action({DZD, - integer()})). -do_index(Continuation, Next) -> - fun() -> case Continuation() of - stop -> - stop; - - {continue, E, Continuation@1} -> - {continue, {E, Next}, do_index(Continuation@1, Next + 1)} - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 787). --spec index(iterator(DZG)) -> iterator({DZG, integer()}). -index(Iterator) -> - _pipe = erlang:element(2, Iterator), - _pipe@1 = do_index(_pipe, 0), - {iterator, _pipe@1}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 802). --spec iterate(DZJ, fun((DZJ) -> DZJ)) -> iterator(DZJ). -iterate(Initial, F) -> - unfold(Initial, fun(Element) -> {next, Element, F(Element)} end). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 809). --spec do_take_while(fun(() -> action(DZL)), fun((DZL) -> boolean())) -> fun(() -> action(DZL)). -do_take_while(Continuation, Predicate) -> - fun() -> case Continuation() of - stop -> - stop; - - {continue, E, Next} -> - case Predicate(E) of - false -> - stop; - - true -> - {continue, E, do_take_while(Next, Predicate)} - end - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 836). --spec take_while(iterator(DZO), fun((DZO) -> boolean())) -> iterator(DZO). -take_while(Iterator, Predicate) -> - _pipe = erlang:element(2, Iterator), - _pipe@1 = do_take_while(_pipe, Predicate), - {iterator, _pipe@1}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 845). --spec do_drop_while(fun(() -> action(DZR)), fun((DZR) -> boolean())) -> action(DZR). -do_drop_while(Continuation, Predicate) -> - case Continuation() of - stop -> - stop; - - {continue, E, Next} -> - case Predicate(E) of - false -> - {continue, E, Next}; - - true -> - do_drop_while(Next, Predicate) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 871). --spec drop_while(iterator(DZU), fun((DZU) -> boolean())) -> iterator(DZU). -drop_while(Iterator, Predicate) -> - _pipe = fun() -> do_drop_while(erlang:element(2, Iterator), Predicate) end, - {iterator, _pipe}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 879). --spec do_scan(fun(() -> action(DZX)), fun((DZZ, DZX) -> DZZ), DZZ) -> fun(() -> action(DZZ)). -do_scan(Continuation, F, Accumulator) -> - fun() -> case Continuation() of - stop -> - stop; - - {continue, El, Next} -> - Accumulated = F(Accumulator, El), - {continue, Accumulated, do_scan(Next, F, Accumulated)} - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 909). --spec scan(iterator(EAB), EAD, fun((EAD, EAB) -> EAD)) -> iterator(EAD). -scan(Iterator, Initial, F) -> - _pipe = erlang:element(2, Iterator), - _pipe@1 = do_scan(_pipe, F, Initial), - {iterator, _pipe@1}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 919). --spec do_zip(fun(() -> action(EAF)), fun(() -> action(EAH))) -> fun(() -> action({EAF, - EAH})). -do_zip(Left, Right) -> - fun() -> case Left() of - stop -> - stop; - - {continue, El_left, Next_left} -> - case Right() of - stop -> - stop; - - {continue, El_right, Next_right} -> - {continue, - {El_left, El_right}, - do_zip(Next_left, Next_right)} - end - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 948). --spec zip(iterator(EAK), iterator(EAM)) -> iterator({EAK, EAM}). -zip(Left, Right) -> - _pipe = do_zip(erlang:element(2, Left), erlang:element(2, Right)), - {iterator, _pipe}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 959). --spec next_chunk(fun(() -> action(EAP)), fun((EAP) -> EAR), EAR, list(EAP)) -> chunk(EAP, EAR). -next_chunk(Continuation, F, Previous_key, Current_chunk) -> - case Continuation() of - stop -> - {last_by, lists:reverse(Current_chunk)}; - - {continue, E, Next} -> - Key = F(E), - case Key =:= Previous_key of - true -> - next_chunk(Next, F, Key, [E | Current_chunk]); - - false -> - {another_by, lists:reverse(Current_chunk), Key, E, Next} - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 977). --spec do_chunk(fun(() -> action(EAV)), fun((EAV) -> EAX), EAX, EAV) -> action(list(EAV)). -do_chunk(Continuation, F, Previous_key, Previous_element) -> - case next_chunk(Continuation, F, Previous_key, [Previous_element]) of - {last_by, Chunk} -> - {continue, Chunk, fun stop/0}; - - {another_by, Chunk@1, Key, El, Next} -> - {continue, Chunk@1, fun() -> do_chunk(Next, F, Key, El) end} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1002). --spec chunk(iterator(EBA), fun((EBA) -> any())) -> iterator(list(EBA)). -chunk(Iterator, F) -> - _pipe = fun() -> case (erlang:element(2, Iterator))() of - stop -> - stop; - - {continue, E, Next} -> - do_chunk(Next, F, F(E), E) - end end, - {iterator, _pipe}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1022). --spec next_sized_chunk(fun(() -> action(EBF)), integer(), list(EBF)) -> sized_chunk(EBF). -next_sized_chunk(Continuation, Left, Current_chunk) -> - case Continuation() of - stop -> - case Current_chunk of - [] -> - no_more; - - Remaining -> - {last, lists:reverse(Remaining)} - end; - - {continue, E, Next} -> - Chunk = [E | Current_chunk], - case Left > 1 of - false -> - {another, lists:reverse(Chunk), Next}; - - true -> - next_sized_chunk(Next, Left - 1, Chunk) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1043). --spec do_sized_chunk(fun(() -> action(EBJ)), integer()) -> fun(() -> action(list(EBJ))). -do_sized_chunk(Continuation, Count) -> - fun() -> case next_sized_chunk(Continuation, Count, []) of - no_more -> - stop; - - {last, Chunk} -> - {continue, Chunk, fun stop/0}; - - {another, Chunk@1, Next_element} -> - {continue, Chunk@1, do_sized_chunk(Next_element, Count)} - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1080). --spec sized_chunk(iterator(EBN), integer()) -> iterator(list(EBN)). -sized_chunk(Iterator, Count) -> - _pipe = erlang:element(2, Iterator), - _pipe@1 = do_sized_chunk(_pipe, Count), - {iterator, _pipe@1}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1089). --spec do_intersperse(fun(() -> action(EBR)), EBR) -> action(EBR). -do_intersperse(Continuation, Separator) -> - case Continuation() of - stop -> - stop; - - {continue, E, Next} -> - Next_interspersed = fun() -> do_intersperse(Next, Separator) end, - {continue, Separator, fun() -> {continue, E, Next_interspersed} end} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1128). --spec intersperse(iterator(EBU), EBU) -> iterator(EBU). -intersperse(Iterator, Elem) -> - _pipe = fun() -> case (erlang:element(2, Iterator))() of - stop -> - stop; - - {continue, E, Next} -> - {continue, E, fun() -> do_intersperse(Next, Elem) end} - end end, - {iterator, _pipe}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1141). --spec do_any(fun(() -> action(EBX)), fun((EBX) -> boolean())) -> boolean(). -do_any(Continuation, Predicate) -> - case Continuation() of - stop -> - false; - - {continue, E, Next} -> - case Predicate(E) of - true -> - true; - - false -> - do_any(Next, Predicate) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1182). --spec any(iterator(EBZ), fun((EBZ) -> boolean())) -> boolean(). -any(Iterator, Predicate) -> - _pipe = erlang:element(2, Iterator), - do_any(_pipe, Predicate). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1190). --spec do_all(fun(() -> action(ECB)), fun((ECB) -> boolean())) -> boolean(). -do_all(Continuation, Predicate) -> - case Continuation() of - stop -> - true; - - {continue, E, Next} -> - case Predicate(E) of - true -> - do_all(Next, Predicate); - - false -> - false - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1231). --spec all(iterator(ECD), fun((ECD) -> boolean())) -> boolean(). -all(Iterator, Predicate) -> - _pipe = erlang:element(2, Iterator), - do_all(_pipe, Predicate). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1239). --spec update_group_with(ECF) -> fun((gleam@option:option(list(ECF))) -> list(ECF)). -update_group_with(El) -> - fun(Maybe_group) -> case Maybe_group of - {some, Group} -> - [El | Group]; - - none -> - [El] - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1248). --spec group_updater(fun((ECJ) -> ECK)) -> fun((gleam@dict:dict(ECK, list(ECJ)), ECJ) -> gleam@dict:dict(ECK, list(ECJ))). -group_updater(F) -> - fun(Groups, Elem) -> _pipe = Groups, - gleam@dict:upsert(_pipe, F(Elem), update_group_with(Elem)) end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1270). --spec group(iterator(ECR), fun((ECR) -> ECT)) -> gleam@dict:dict(ECT, list(ECR)). -group(Iterator, Key) -> - _pipe = Iterator, - _pipe@1 = fold(_pipe, gleam@dict:new(), group_updater(Key)), - gleam@dict:map_values(_pipe@1, fun(_, Group) -> lists:reverse(Group) end). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1300). --spec reduce(iterator(ECX), fun((ECX, ECX) -> ECX)) -> {ok, ECX} | {error, nil}. -reduce(Iterator, F) -> - case (erlang:element(2, Iterator))() of - stop -> - {error, nil}; - - {continue, E, Next} -> - _pipe = do_fold(Next, F, E), - {ok, _pipe} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1330). --spec last(iterator(EDB)) -> {ok, EDB} | {error, nil}. -last(Iterator) -> - _pipe = Iterator, - reduce(_pipe, fun(_, Elem) -> Elem end). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1344). --spec empty() -> iterator(any()). -empty() -> - {iterator, fun stop/0}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1357). --spec once(fun(() -> EDH)) -> iterator(EDH). -once(F) -> - _pipe = fun() -> {continue, F(), fun stop/0} end, - {iterator, _pipe}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 657). --spec range(integer(), integer()) -> iterator(integer()). -range(Start, Stop) -> - case gleam@int:compare(Start, Stop) of - eq -> - once(fun() -> Start end); - - gt -> - unfold(Start, fun(Current) -> case Current < Stop of - false -> - {next, Current, Current - 1}; - - true -> - done - end end); - - lt -> - unfold(Start, fun(Current@1) -> case Current@1 > Stop of - false -> - {next, Current@1, Current@1 + 1}; - - true -> - done - end end) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1371). --spec single(EDJ) -> iterator(EDJ). -single(Elem) -> - once(fun() -> Elem end). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1375). --spec do_interleave(fun(() -> action(EDL)), fun(() -> action(EDL))) -> action(EDL). -do_interleave(Current, Next) -> - case Current() of - stop -> - Next(); - - {continue, E, Next_other} -> - {continue, E, fun() -> do_interleave(Next, Next_other) end} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1405). --spec interleave(iterator(EDP), iterator(EDP)) -> iterator(EDP). -interleave(Left, Right) -> - _pipe = fun() -> - do_interleave(erlang:element(2, Left), erlang:element(2, Right)) - end, - {iterator, _pipe}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1413). --spec do_fold_until( - fun(() -> action(EDT)), - fun((EDV, EDT) -> gleam@list:continue_or_stop(EDV)), - EDV -) -> EDV. -do_fold_until(Continuation, F, Accumulator) -> - case Continuation() of - stop -> - Accumulator; - - {continue, Elem, Next} -> - case F(Accumulator, Elem) of - {continue, Accumulator@1} -> - do_fold_until(Next, F, Accumulator@1); - - {stop, Accumulator@2} -> - Accumulator@2 - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1452). --spec fold_until( - iterator(EDX), - EDZ, - fun((EDZ, EDX) -> gleam@list:continue_or_stop(EDZ)) -) -> EDZ. -fold_until(Iterator, Initial, F) -> - _pipe = erlang:element(2, Iterator), - do_fold_until(_pipe, F, Initial). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1461). --spec do_try_fold( - fun(() -> action(EEB)), - fun((EED, EEB) -> {ok, EED} | {error, EEE}), - EED -) -> {ok, EED} | {error, EEE}. -do_try_fold(Continuation, F, Accumulator) -> - case Continuation() of - stop -> - {ok, Accumulator}; - - {continue, Elem, Next} -> - case F(Accumulator, Elem) of - {ok, Result} -> - do_try_fold(Next, F, Result); - - {error, _} = Error -> - Error - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1496). --spec try_fold(iterator(EEJ), EEL, fun((EEL, EEJ) -> {ok, EEL} | {error, EEM})) -> {ok, - EEL} | - {error, EEM}. -try_fold(Iterator, Initial, F) -> - _pipe = erlang:element(2, Iterator), - do_try_fold(_pipe, F, Initial). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1519). --spec first(iterator(EER)) -> {ok, EER} | {error, nil}. -first(Iterator) -> - case (erlang:element(2, Iterator))() of - stop -> - {error, nil}; - - {continue, E, _} -> - {ok, E} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1549). --spec at(iterator(EEV), integer()) -> {ok, EEV} | {error, nil}. -at(Iterator, Index) -> - _pipe = Iterator, - _pipe@1 = drop(_pipe, Index), - first(_pipe@1). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1555). --spec do_length(fun(() -> action(any())), integer()) -> integer(). -do_length(Continuation, Length) -> - case Continuation() of - stop -> - Length; - - {continue, _, Next} -> - do_length(Next, Length + 1) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1579). --spec length(iterator(any())) -> integer(). -length(Iterator) -> - _pipe = erlang:element(2, Iterator), - do_length(_pipe, 0). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1601). --spec each(iterator(EFD), fun((EFD) -> any())) -> nil. -each(Iterator, F) -> - _pipe = Iterator, - _pipe@1 = map(_pipe, F), - run(_pipe@1). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1626). --spec yield(EFG, fun(() -> iterator(EFG))) -> iterator(EFG). -yield(Element, Next) -> - {iterator, - fun() -> - {continue, Element, fun() -> (erlang:element(2, Next()))() end} - end}. diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@list.erl b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@list.erl deleted file mode 100644 index fb2164d3f01..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@list.erl +++ /dev/null @@ -1,1442 +0,0 @@ --module(gleam@list). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([length/1, reverse/1, is_empty/1, contains/2, first/1, rest/1, filter/2, filter_map/2, map/2, map2/3, index_map/2, try_map/2, drop/2, take/2, new/0, wrap/1, append/2, prepend/2, concat/1, flatten/1, flat_map/2, fold/3, count/2, group/2, map_fold/3, fold_right/3, index_fold/3, try_fold/3, fold_until/3, find/2, find_map/2, all/2, any/2, zip/2, strict_zip/2, unzip/1, intersperse/2, unique/1, sort/2, range/2, repeat/2, split/2, split_while/2, key_find/2, key_filter/2, pop/2, pop_map/2, key_pop/2, key_set/3, each/2, try_each/2, partition/2, permutations/1, window/2, window_by_2/1, drop_while/2, take_while/2, chunk/2, sized_chunk/2, reduce/2, scan/3, last/1, combinations/2, combination_pairs/1, transpose/1, interleave/1, shuffle/1]). --export_type([continue_or_stop/1, sorting/0]). - --type continue_or_stop(AAO) :: {continue, AAO} | {stop, AAO}. - --type sorting() :: ascending | descending. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 61). --spec count_length(list(any()), integer()) -> integer(). -count_length(List, Count) -> - case List of - [_ | List@1] -> - count_length(List@1, Count + 1); - - _ -> - Count - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 57). --spec length(list(any())) -> integer(). -length(List) -> - erlang:length(List). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 130). --spec do_reverse(list(AAY), list(AAY)) -> list(AAY). -do_reverse(Remaining, Accumulator) -> - case Remaining of - [] -> - Accumulator; - - [Item | Rest] -> - do_reverse(Rest, [Item | Accumulator]) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 126). --spec reverse(list(AAV)) -> list(AAV). -reverse(List) -> - lists:reverse(List). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 158). --spec is_empty(list(any())) -> boolean(). -is_empty(List) -> - List =:= []. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 194). --spec contains(list(ABE), ABE) -> boolean(). -contains(List, Elem) -> - case List of - [] -> - false; - - [First | _] when First =:= Elem -> - true; - - [_ | Rest] -> - contains(Rest, Elem) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 221). --spec first(list(ABG)) -> {ok, ABG} | {error, nil}. -first(List) -> - case List of - [] -> - {error, nil}; - - [X | _] -> - {ok, X} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 250). --spec rest(list(ABK)) -> {ok, list(ABK)} | {error, nil}. -rest(List) -> - case List of - [] -> - {error, nil}; - - [_ | Rest] -> - {ok, Rest} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 257). --spec update_group(fun((ABP) -> ABQ)) -> fun((gleam@dict:dict(ABQ, list(ABP)), ABP) -> gleam@dict:dict(ABQ, list(ABP))). -update_group(F) -> - fun(Groups, Elem) -> case gleam@dict:get(Groups, F(Elem)) of - {ok, Existing} -> - gleam@dict:insert(Groups, F(Elem), [Elem | Existing]); - - {error, _} -> - gleam@dict:insert(Groups, F(Elem), [Elem]) - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 302). --spec do_filter(list(ACD), fun((ACD) -> boolean()), list(ACD)) -> list(ACD). -do_filter(List, Fun, Acc) -> - case List of - [] -> - lists:reverse(Acc); - - [First | Rest] -> - New_acc = case Fun(First) of - true -> - [First | Acc]; - - false -> - Acc - end, - do_filter(Rest, Fun, New_acc) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 330). --spec filter(list(ACH), fun((ACH) -> boolean())) -> list(ACH). -filter(List, Predicate) -> - do_filter(List, Predicate, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 334). --spec do_filter_map( - list(ACK), - fun((ACK) -> {ok, ACM} | {error, any()}), - list(ACM) -) -> list(ACM). -do_filter_map(List, Fun, Acc) -> - case List of - [] -> - lists:reverse(Acc); - - [First | Rest] -> - New_acc = case Fun(First) of - {ok, First@1} -> - [First@1 | Acc]; - - {error, _} -> - Acc - end, - do_filter_map(Rest, Fun, New_acc) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 366). --spec filter_map(list(ACS), fun((ACS) -> {ok, ACU} | {error, any()})) -> list(ACU). -filter_map(List, Fun) -> - do_filter_map(List, Fun, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 370). --spec do_map(list(ACZ), fun((ACZ) -> ADB), list(ADB)) -> list(ADB). -do_map(List, Fun, Acc) -> - case List of - [] -> - lists:reverse(Acc); - - [First | Rest] -> - do_map(Rest, Fun, [Fun(First) | Acc]) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 387). --spec map(list(ADE), fun((ADE) -> ADG)) -> list(ADG). -map(List, Fun) -> - do_map(List, Fun, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 411). --spec do_map2(list(ADO), list(ADQ), fun((ADO, ADQ) -> ADS), list(ADS)) -> list(ADS). -do_map2(List1, List2, Fun, Acc) -> - case {List1, List2} of - {[], _} -> - lists:reverse(Acc); - - {_, []} -> - lists:reverse(Acc); - - {[A | As_], [B | Bs]} -> - do_map2(As_, Bs, Fun, [Fun(A, B) | Acc]) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 407). --spec map2(list(ADI), list(ADK), fun((ADI, ADK) -> ADM)) -> list(ADM). -map2(List1, List2, Fun) -> - do_map2(List1, List2, Fun, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 449). --spec do_index_map( - list(AEA), - fun((AEA, integer()) -> AEC), - integer(), - list(AEC) -) -> list(AEC). -do_index_map(List, Fun, Index, Acc) -> - case List of - [] -> - lists:reverse(Acc); - - [First | Rest] -> - Acc@1 = [Fun(First, Index) | Acc], - do_index_map(Rest, Fun, Index + 1, Acc@1) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 477). --spec index_map(list(AEF), fun((AEF, integer()) -> AEH)) -> list(AEH). -index_map(List, Fun) -> - do_index_map(List, Fun, 0, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 481). --spec do_try_map(list(AEJ), fun((AEJ) -> {ok, AEL} | {error, AEM}), list(AEL)) -> {ok, - list(AEL)} | - {error, AEM}. -do_try_map(List, Fun, Acc) -> - case List of - [] -> - {ok, lists:reverse(Acc)}; - - [First | Rest] -> - case Fun(First) of - {ok, First@1} -> - do_try_map(Rest, Fun, [First@1 | Acc]); - - {error, Error} -> - {error, Error} - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 528). --spec try_map(list(AET), fun((AET) -> {ok, AEV} | {error, AEW})) -> {ok, - list(AEV)} | - {error, AEW}. -try_map(List, Fun) -> - do_try_map(List, Fun, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 555). --spec drop(list(AFC), integer()) -> list(AFC). -drop(List, N) -> - case N =< 0 of - true -> - List; - - false -> - case List of - [] -> - []; - - [_ | Rest] -> - drop(Rest, N - 1) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 566). --spec do_take(list(AFF), integer(), list(AFF)) -> list(AFF). -do_take(List, N, Acc) -> - case N =< 0 of - true -> - lists:reverse(Acc); - - false -> - case List of - [] -> - lists:reverse(Acc); - - [First | Rest] -> - do_take(Rest, N - 1, [First | Acc]) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 597). --spec take(list(AFJ), integer()) -> list(AFJ). -take(List, N) -> - do_take(List, N, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 610). --spec new() -> list(any()). -new() -> - []. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 630). --spec wrap(AFO) -> list(AFO). -wrap(Item) -> - [Item]. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 651). --spec do_append(list(AFU), list(AFU)) -> list(AFU). -do_append(First, Second) -> - case First of - [] -> - Second; - - [Item | Rest] -> - do_append(Rest, [Item | Second]) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 647). --spec append(list(AFQ), list(AFQ)) -> list(AFQ). -append(First, Second) -> - lists:append(First, Second). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 671). --spec prepend(list(AFY), AFY) -> list(AFY). -prepend(List, Item) -> - [Item | List]. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 676). --spec reverse_and_prepend(list(AGB), list(AGB)) -> list(AGB). -reverse_and_prepend(Prefix, Suffix) -> - case Prefix of - [] -> - Suffix; - - [First | Rest] -> - reverse_and_prepend(Rest, [First | Suffix]) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 683). --spec do_concat(list(list(AGF)), list(AGF)) -> list(AGF). -do_concat(Lists, Acc) -> - case Lists of - [] -> - lists:reverse(Acc); - - [List | Further_lists] -> - do_concat(Further_lists, reverse_and_prepend(List, Acc)) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 703). --spec concat(list(list(AGK))) -> list(AGK). -concat(Lists) -> - do_concat(Lists, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 719). --spec flatten(list(list(AGO))) -> list(AGO). -flatten(Lists) -> - do_concat(Lists, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 732). --spec flat_map(list(AGS), fun((AGS) -> list(AGU))) -> list(AGU). -flat_map(List, Fun) -> - _pipe = map(List, Fun), - flatten(_pipe). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 745). --spec fold(list(AGX), AGZ, fun((AGZ, AGX) -> AGZ)) -> AGZ. -fold(List, Initial, Fun) -> - case List of - [] -> - Initial; - - [X | Rest] -> - fold(Rest, Fun(Initial, X), Fun) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 90). --spec count(list(AAT), fun((AAT) -> boolean())) -> integer(). -count(List, Predicate) -> - fold(List, 0, fun(Acc, Value) -> case Predicate(Value) of - true -> - Acc + 1; - - false -> - Acc - end end). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 298). --spec group(list(ABX), fun((ABX) -> ABZ)) -> gleam@dict:dict(ABZ, list(ABX)). -group(List, Key) -> - fold(List, gleam@dict:new(), update_group(Key)). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 436). --spec map_fold(list(ADV), ADX, fun((ADX, ADV) -> {ADX, ADY})) -> {ADX, - list(ADY)}. -map_fold(List, Initial, Fun) -> - _pipe = fold( - List, - {Initial, []}, - fun(Acc, Item) -> - {Current_acc, Items} = Acc, - {Next_acc, Next_item} = Fun(Current_acc, Item), - {Next_acc, [Next_item | Items]} - end - ), - gleam@pair:map_second(_pipe, fun lists:reverse/1). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 767). --spec fold_right(list(AHA), AHC, fun((AHC, AHA) -> AHC)) -> AHC. -fold_right(List, Initial, Fun) -> - case List of - [] -> - Initial; - - [X | Rest] -> - Fun(fold_right(Rest, Initial, Fun), X) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 778). --spec do_index_fold( - list(AHD), - AHF, - fun((AHF, AHD, integer()) -> AHF), - integer() -) -> AHF. -do_index_fold(Over, Acc, With, Index) -> - case Over of - [] -> - Acc; - - [First | Rest] -> - do_index_fold(Rest, With(Acc, First, Index), With, Index + 1) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 800). --spec index_fold(list(AHG), AHI, fun((AHI, AHG, integer()) -> AHI)) -> AHI. -index_fold(List, Initial, Fun) -> - do_index_fold(List, Initial, Fun, 0). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 827). --spec try_fold(list(AHJ), AHL, fun((AHL, AHJ) -> {ok, AHL} | {error, AHM})) -> {ok, - AHL} | - {error, AHM}. -try_fold(List, Initial, Fun) -> - case List of - [] -> - {ok, Initial}; - - [First | Rest] -> - case Fun(Initial, First) of - {ok, Result} -> - try_fold(Rest, Result, Fun); - - {error, _} = Error -> - Error - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 866). --spec fold_until(list(AHR), AHT, fun((AHT, AHR) -> continue_or_stop(AHT))) -> AHT. -fold_until(List, Initial, Fun) -> - case List of - [] -> - Initial; - - [First | Rest] -> - case Fun(Initial, First) of - {continue, Next_accumulator} -> - fold_until(Rest, Next_accumulator, Fun); - - {stop, B} -> - B - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 903). --spec find(list(AHV), fun((AHV) -> boolean())) -> {ok, AHV} | {error, nil}. -find(List, Is_desired) -> - case List of - [] -> - {error, nil}; - - [X | Rest] -> - case Is_desired(X) of - true -> - {ok, X}; - - _ -> - find(Rest, Is_desired) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 939). --spec find_map(list(AHZ), fun((AHZ) -> {ok, AIB} | {error, any()})) -> {ok, AIB} | - {error, nil}. -find_map(List, Fun) -> - case List of - [] -> - {error, nil}; - - [X | Rest] -> - case Fun(X) of - {ok, X@1} -> - {ok, X@1}; - - _ -> - find_map(Rest, Fun) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 974). --spec all(list(AIH), fun((AIH) -> boolean())) -> boolean(). -all(List, Predicate) -> - case List of - [] -> - true; - - [First | Rest] -> - case Predicate(First) of - true -> - all(Rest, Predicate); - - false -> - false - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1011). --spec any(list(AIJ), fun((AIJ) -> boolean())) -> boolean(). -any(List, Predicate) -> - case List of - [] -> - false; - - [First | Rest] -> - case Predicate(First) of - true -> - true; - - false -> - any(Rest, Predicate) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1022). --spec do_zip(list(AIL), list(AIN), list({AIL, AIN})) -> list({AIL, AIN}). -do_zip(One, Other, Acc) -> - case {One, Other} of - {[First_one | Rest_one], [First_other | Rest_other]} -> - do_zip(Rest_one, Rest_other, [{First_one, First_other} | Acc]); - - {_, _} -> - lists:reverse(Acc) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1057). --spec zip(list(AIR), list(AIT)) -> list({AIR, AIT}). -zip(List, Other) -> - do_zip(List, Other, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1087). --spec strict_zip(list(AIW), list(AIY)) -> {ok, list({AIW, AIY})} | {error, nil}. -strict_zip(List, Other) -> - case erlang:length(List) =:= erlang:length(Other) of - true -> - {ok, zip(List, Other)}; - - false -> - {error, nil} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1097). --spec do_unzip(list({AJD, AJE}), list(AJD), list(AJE)) -> {list(AJD), list(AJE)}. -do_unzip(Input, One, Other) -> - case Input of - [] -> - {lists:reverse(One), lists:reverse(Other)}; - - [{First_one, First_other} | Rest] -> - do_unzip(Rest, [First_one | One], [First_other | Other]) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1123). --spec unzip(list({AJK, AJL})) -> {list(AJK), list(AJL)}. -unzip(Input) -> - do_unzip(Input, [], []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1127). --spec do_intersperse(list(AJP), AJP, list(AJP)) -> list(AJP). -do_intersperse(List, Separator, Acc) -> - case List of - [] -> - lists:reverse(Acc); - - [X | Rest] -> - do_intersperse(Rest, Separator, [X, Separator | Acc]) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1150). --spec intersperse(list(AJT), AJT) -> list(AJT). -intersperse(List, Elem) -> - case List of - [] -> - List; - - [_] -> - List; - - [X | Rest] -> - do_intersperse(Rest, Elem, [X]) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1168). --spec unique(list(AJW)) -> list(AJW). -unique(List) -> - case List of - [] -> - []; - - [X | Rest] -> - [X | unique(filter(Rest, fun(Y) -> Y /= X end))] - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1249). --spec sequences( - list(AKC), - fun((AKC, AKC) -> gleam@order:order()), - list(AKC), - sorting(), - AKC, - list(list(AKC)) -) -> list(list(AKC)). -sequences(List, Compare, Growing, Direction, Prev, Acc) -> - Growing@1 = [Prev | Growing], - case List of - [] -> - case Direction of - ascending -> - [do_reverse(Growing@1, []) | Acc]; - - descending -> - [Growing@1 | Acc] - end; - - [New | Rest] -> - case {Compare(Prev, New), Direction} of - {gt, descending} -> - sequences(Rest, Compare, Growing@1, Direction, New, Acc); - - {lt, ascending} -> - sequences(Rest, Compare, Growing@1, Direction, New, Acc); - - {eq, ascending} -> - sequences(Rest, Compare, Growing@1, Direction, New, Acc); - - {gt, ascending} -> - Acc@1 = case Direction of - ascending -> - [do_reverse(Growing@1, []) | Acc]; - - descending -> - [Growing@1 | Acc] - end, - case Rest of - [] -> - [[New] | Acc@1]; - - [Next | Rest@1] -> - Direction@1 = case Compare(New, Next) of - lt -> - ascending; - - eq -> - ascending; - - gt -> - descending - end, - sequences( - Rest@1, - Compare, - [New], - Direction@1, - Next, - Acc@1 - ) - end; - - {lt, descending} -> - Acc@1 = case Direction of - ascending -> - [do_reverse(Growing@1, []) | Acc]; - - descending -> - [Growing@1 | Acc] - end, - case Rest of - [] -> - [[New] | Acc@1]; - - [Next | Rest@1] -> - Direction@1 = case Compare(New, Next) of - lt -> - ascending; - - eq -> - ascending; - - gt -> - descending - end, - sequences( - Rest@1, - Compare, - [New], - Direction@1, - Next, - Acc@1 - ) - end; - - {eq, descending} -> - Acc@1 = case Direction of - ascending -> - [do_reverse(Growing@1, []) | Acc]; - - descending -> - [Growing@1 | Acc] - end, - case Rest of - [] -> - [[New] | Acc@1]; - - [Next | Rest@1] -> - Direction@1 = case Compare(New, Next) of - lt -> - ascending; - - eq -> - ascending; - - gt -> - descending - end, - sequences( - Rest@1, - Compare, - [New], - Direction@1, - Next, - Acc@1 - ) - end - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1397). --spec merge_ascendings( - list(AKZ), - list(AKZ), - fun((AKZ, AKZ) -> gleam@order:order()), - list(AKZ) -) -> list(AKZ). -merge_ascendings(List1, List2, Compare, Acc) -> - case {List1, List2} of - {[], List} -> - do_reverse(List, Acc); - - {List, []} -> - do_reverse(List, Acc); - - {[First1 | Rest1], [First2 | Rest2]} -> - case Compare(First1, First2) of - lt -> - merge_ascendings(Rest1, List2, Compare, [First1 | Acc]); - - gt -> - merge_ascendings(List1, Rest2, Compare, [First2 | Acc]); - - eq -> - merge_ascendings(List1, Rest2, Compare, [First2 | Acc]) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1350). --spec merge_ascending_pairs( - list(list(AKN)), - fun((AKN, AKN) -> gleam@order:order()), - list(list(AKN)) -) -> list(list(AKN)). -merge_ascending_pairs(Sequences, Compare, Acc) -> - case Sequences of - [] -> - do_reverse(Acc, []); - - [Sequence] -> - do_reverse([do_reverse(Sequence, []) | Acc], []); - - [Ascending1, Ascending2 | Rest] -> - Descending = merge_ascendings(Ascending1, Ascending2, Compare, []), - merge_ascending_pairs(Rest, Compare, [Descending | Acc]) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1424). --spec merge_descendings( - list(ALE), - list(ALE), - fun((ALE, ALE) -> gleam@order:order()), - list(ALE) -) -> list(ALE). -merge_descendings(List1, List2, Compare, Acc) -> - case {List1, List2} of - {[], List} -> - do_reverse(List, Acc); - - {List, []} -> - do_reverse(List, Acc); - - {[First1 | Rest1], [First2 | Rest2]} -> - case Compare(First1, First2) of - lt -> - merge_descendings(List1, Rest2, Compare, [First2 | Acc]); - - gt -> - merge_descendings(Rest1, List2, Compare, [First1 | Acc]); - - eq -> - merge_descendings(Rest1, List2, Compare, [First1 | Acc]) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1372). --spec merge_descending_pairs( - list(list(AKT)), - fun((AKT, AKT) -> gleam@order:order()), - list(list(AKT)) -) -> list(list(AKT)). -merge_descending_pairs(Sequences, Compare, Acc) -> - case Sequences of - [] -> - do_reverse(Acc, []); - - [Sequence] -> - do_reverse([do_reverse(Sequence, []) | Acc], []); - - [Descending1, Descending2 | Rest] -> - Ascending = merge_descendings(Descending1, Descending2, Compare, []), - merge_descending_pairs(Rest, Compare, [Ascending | Acc]) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1316). --spec merge_all( - list(list(AKJ)), - sorting(), - fun((AKJ, AKJ) -> gleam@order:order()) -) -> list(AKJ). -merge_all(Sequences, Direction, Compare) -> - case {Sequences, Direction} of - {[], _} -> - []; - - {[Sequence], ascending} -> - Sequence; - - {[Sequence@1], descending} -> - do_reverse(Sequence@1, []); - - {_, ascending} -> - Sequences@1 = merge_ascending_pairs(Sequences, Compare, []), - merge_all(Sequences@1, descending, Compare); - - {_, descending} -> - Sequences@2 = merge_descending_pairs(Sequences, Compare, []), - merge_all(Sequences@2, ascending, Compare) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1187). --spec sort(list(AJZ), fun((AJZ, AJZ) -> gleam@order:order())) -> list(AJZ). -sort(List, Compare) -> - case List of - [] -> - []; - - [X] -> - [X]; - - [X@1, Y | Rest] -> - Direction = case Compare(X@1, Y) of - lt -> - ascending; - - eq -> - ascending; - - gt -> - descending - end, - Sequences = sequences(Rest, Compare, [X@1], Direction, Y, []), - merge_all(Sequences, ascending, Compare) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1464). --spec tail_recursive_range(integer(), integer(), list(integer())) -> list(integer()). -tail_recursive_range(Start, Stop, Acc) -> - case gleam@int:compare(Start, Stop) of - eq -> - [Stop | Acc]; - - gt -> - tail_recursive_range(Start, Stop + 1, [Stop | Acc]); - - lt -> - tail_recursive_range(Start, Stop - 1, [Stop | Acc]) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1460). --spec range(integer(), integer()) -> list(integer()). -range(Start, Stop) -> - tail_recursive_range(Start, Stop, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1472). --spec do_repeat(ALM, integer(), list(ALM)) -> list(ALM). -do_repeat(Item, Times, Acc) -> - case Times =< 0 of - true -> - Acc; - - false -> - do_repeat(Item, Times - 1, [Item | Acc]) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1493). --spec repeat(ALP, integer()) -> list(ALP). -repeat(A, Times) -> - do_repeat(A, Times, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1497). --spec do_split(list(ALR), integer(), list(ALR)) -> {list(ALR), list(ALR)}. -do_split(List, N, Taken) -> - case N =< 0 of - true -> - {lists:reverse(Taken), List}; - - false -> - case List of - [] -> - {lists:reverse(Taken), []}; - - [First | Rest] -> - do_split(Rest, N - 1, [First | Taken]) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1530). --spec split(list(ALW), integer()) -> {list(ALW), list(ALW)}. -split(List, Index) -> - do_split(List, Index, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1534). --spec do_split_while(list(AMA), fun((AMA) -> boolean()), list(AMA)) -> {list(AMA), - list(AMA)}. -do_split_while(List, F, Acc) -> - case List of - [] -> - {lists:reverse(Acc), []}; - - [First | Rest] -> - case F(First) of - false -> - {lists:reverse(Acc), List}; - - _ -> - do_split_while(Rest, F, [First | Acc]) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1567). --spec split_while(list(AMF), fun((AMF) -> boolean())) -> {list(AMF), list(AMF)}. -split_while(List, Predicate) -> - do_split_while(List, Predicate, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1599). --spec key_find(list({AMJ, AMK}), AMJ) -> {ok, AMK} | {error, nil}. -key_find(Keyword_list, Desired_key) -> - find_map( - Keyword_list, - fun(Keyword) -> - {Key, Value} = Keyword, - case Key =:= Desired_key of - true -> - {ok, Value}; - - false -> - {error, nil} - end - end - ). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1630). --spec key_filter(list({AMO, AMP}), AMO) -> list(AMP). -key_filter(Keyword_list, Desired_key) -> - filter_map( - Keyword_list, - fun(Keyword) -> - {Key, Value} = Keyword, - case Key =:= Desired_key of - true -> - {ok, Value}; - - false -> - {error, nil} - end - end - ). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1643). --spec do_pop(list(BEX), fun((BEX) -> boolean()), list(BEX)) -> {ok, - {BEX, list(BEX)}} | - {error, nil}. -do_pop(Haystack, Predicate, Checked) -> - case Haystack of - [] -> - {error, nil}; - - [X | Rest] -> - case Predicate(X) of - true -> - {ok, {X, lists:append(lists:reverse(Checked), Rest)}}; - - false -> - do_pop(Rest, Predicate, [X | Checked]) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1675). --spec pop(list(AMW), fun((AMW) -> boolean())) -> {ok, {AMW, list(AMW)}} | - {error, nil}. -pop(List, Is_desired) -> - do_pop(List, Is_desired, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1682). --spec do_pop_map(list(ANB), fun((ANB) -> {ok, AND} | {error, any()}), list(ANB)) -> {ok, - {AND, list(ANB)}} | - {error, nil}. -do_pop_map(List, Mapper, Checked) -> - case List of - [] -> - {error, nil}; - - [X | Rest] -> - case Mapper(X) of - {ok, Y} -> - {ok, {Y, lists:append(lists:reverse(Checked), Rest)}}; - - {error, _} -> - do_pop_map(Rest, Mapper, [X | Checked]) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1719). --spec pop_map(list(ANL), fun((ANL) -> {ok, ANN} | {error, any()})) -> {ok, - {ANN, list(ANL)}} | - {error, nil}. -pop_map(Haystack, Is_desired) -> - do_pop_map(Haystack, Is_desired, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1749). --spec key_pop(list({ANU, ANV}), ANU) -> {ok, {ANV, list({ANU, ANV})}} | - {error, nil}. -key_pop(List, Key) -> - pop_map( - List, - fun(Entry) -> - {K, V} = Entry, - case K of - K@1 when K@1 =:= Key -> - {ok, V}; - - _ -> - {error, nil} - end - end - ). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1776). --spec key_set(list({AOA, AOB}), AOA, AOB) -> list({AOA, AOB}). -key_set(List, Key, Value) -> - case List of - [] -> - [{Key, Value}]; - - [{K, _} | Rest] when K =:= Key -> - [{Key, Value} | Rest]; - - [First | Rest@1] -> - [First | key_set(Rest@1, Key, Value)] - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1798). --spec each(list(AOE), fun((AOE) -> any())) -> nil. -each(List, F) -> - case List of - [] -> - nil; - - [First | Rest] -> - F(First), - each(Rest, F) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1824). --spec try_each(list(AOH), fun((AOH) -> {ok, any()} | {error, AOK})) -> {ok, nil} | - {error, AOK}. -try_each(List, Fun) -> - case List of - [] -> - {ok, nil}; - - [First | Rest] -> - case Fun(First) of - {ok, _} -> - try_each(Rest, Fun); - - {error, E} -> - {error, E} - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1838). --spec do_partition(list(BHC), fun((BHC) -> boolean()), list(BHC), list(BHC)) -> {list(BHC), - list(BHC)}. -do_partition(List, Categorise, Trues, Falses) -> - case List of - [] -> - {lists:reverse(Trues), lists:reverse(Falses)}; - - [First | Rest] -> - case Categorise(First) of - true -> - do_partition(Rest, Categorise, [First | Trues], Falses); - - false -> - do_partition(Rest, Categorise, Trues, [First | Falses]) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1861). --spec partition(list(AOU), fun((AOU) -> boolean())) -> {list(AOU), list(AOU)}. -partition(List, Categorise) -> - do_partition(List, Categorise, [], []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1877). --spec permutations(list(AOY)) -> list(list(AOY)). -permutations(List) -> - case List of - [] -> - [[]]; - - _ -> - _pipe@3 = index_map( - List, - fun(I, I_idx) -> - _pipe = index_fold( - List, - [], - fun(Acc, J, J_idx) -> case I_idx =:= J_idx of - true -> - Acc; - - false -> - [J | Acc] - end end - ), - _pipe@1 = lists:reverse(_pipe), - _pipe@2 = permutations(_pipe@1), - map(_pipe@2, fun(Permutation) -> [I | Permutation] end) - end - ), - flatten(_pipe@3) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1896). --spec do_window(list(list(APC)), list(APC), integer()) -> list(list(APC)). -do_window(Acc, List, N) -> - Window = take(List, N), - case erlang:length(Window) =:= N of - true -> - do_window([Window | Acc], drop(List, 1), N); - - false -> - Acc - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1919). --spec window(list(API), integer()) -> list(list(API)). -window(List, N) -> - case N =< 0 of - true -> - []; - - false -> - _pipe = do_window([], List, N), - lists:reverse(_pipe) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1940). --spec window_by_2(list(APM)) -> list({APM, APM}). -window_by_2(List) -> - zip(List, drop(List, 1)). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1953). --spec drop_while(list(APP), fun((APP) -> boolean())) -> list(APP). -drop_while(List, Predicate) -> - case List of - [] -> - []; - - [First | Rest] -> - case Predicate(First) of - true -> - drop_while(Rest, Predicate); - - false -> - [First | Rest] - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1967). --spec do_take_while(list(APS), fun((APS) -> boolean()), list(APS)) -> list(APS). -do_take_while(List, Predicate, Acc) -> - case List of - [] -> - lists:reverse(Acc); - - [First | Rest] -> - case Predicate(First) of - true -> - do_take_while(Rest, Predicate, [First | Acc]); - - false -> - lists:reverse(Acc) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1991). --spec take_while(list(APW), fun((APW) -> boolean())) -> list(APW). -take_while(List, Predicate) -> - do_take_while(List, Predicate, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1998). --spec do_chunk(list(APZ), fun((APZ) -> AQB), AQB, list(APZ), list(list(APZ))) -> list(list(APZ)). -do_chunk(List, F, Previous_key, Current_chunk, Acc) -> - case List of - [First | Rest] -> - Key = F(First), - case Key =:= Previous_key of - false -> - New_acc = [lists:reverse(Current_chunk) | Acc], - do_chunk(Rest, F, Key, [First], New_acc); - - _ -> - do_chunk(Rest, F, Key, [First | Current_chunk], Acc) - end; - - _ -> - lists:reverse([lists:reverse(Current_chunk) | Acc]) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 2030). --spec chunk(list(AQH), fun((AQH) -> any())) -> list(list(AQH)). -chunk(List, F) -> - case List of - [] -> - []; - - [First | Rest] -> - do_chunk(Rest, F, F(First), [First], []) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 2037). --spec do_sized_chunk( - list(AQM), - integer(), - integer(), - list(AQM), - list(list(AQM)) -) -> list(list(AQM)). -do_sized_chunk(List, Count, Left, Current_chunk, Acc) -> - case List of - [] -> - case Current_chunk of - [] -> - lists:reverse(Acc); - - Remaining -> - lists:reverse([lists:reverse(Remaining) | Acc]) - end; - - [First | Rest] -> - Chunk = [First | Current_chunk], - case Left > 1 of - false -> - do_sized_chunk( - Rest, - Count, - Count, - [], - [lists:reverse(Chunk) | Acc] - ); - - true -> - do_sized_chunk(Rest, Count, Left - 1, Chunk, Acc) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 2079). --spec sized_chunk(list(AQT), integer()) -> list(list(AQT)). -sized_chunk(List, Count) -> - do_sized_chunk(List, Count, Count, [], []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 2103). --spec reduce(list(AQX), fun((AQX, AQX) -> AQX)) -> {ok, AQX} | {error, nil}. -reduce(List, Fun) -> - case List of - [] -> - {error, nil}; - - [First | Rest] -> - {ok, fold(Rest, First, Fun)} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 2110). --spec do_scan(list(ARB), ARD, list(ARD), fun((ARD, ARB) -> ARD)) -> list(ARD). -do_scan(List, Accumulator, Accumulated, Fun) -> - case List of - [] -> - lists:reverse(Accumulated); - - [First | Rest] -> - Next = Fun(Accumulator, First), - do_scan(Rest, Next, [Next | Accumulated], Fun) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 2134). --spec scan(list(ARG), ARI, fun((ARI, ARG) -> ARI)) -> list(ARI). -scan(List, Initial, Fun) -> - do_scan(List, Initial, [], Fun). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 2162). --spec last(list(ARK)) -> {ok, ARK} | {error, nil}. -last(List) -> - _pipe = List, - reduce(_pipe, fun(_, Elem) -> Elem end). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 2181). --spec combinations(list(ARO), integer()) -> list(list(ARO)). -combinations(Items, N) -> - case N of - 0 -> - [[]]; - - _ -> - case Items of - [] -> - []; - - [First | Rest] -> - First_combinations = begin - _pipe = map( - combinations(Rest, N - 1), - fun(Com) -> [First | Com] end - ), - lists:reverse(_pipe) - end, - fold( - First_combinations, - combinations(Rest, N), - fun(Acc, C) -> [C | Acc] end - ) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 2199). --spec do_combination_pairs(list(ARS)) -> list(list({ARS, ARS})). -do_combination_pairs(Items) -> - case Items of - [] -> - []; - - [First | Rest] -> - First_combinations = map(Rest, fun(Other) -> {First, Other} end), - [First_combinations | do_combination_pairs(Rest)] - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 2218). --spec combination_pairs(list(ARW)) -> list({ARW, ARW}). -combination_pairs(Items) -> - _pipe = do_combination_pairs(Items), - flatten(_pipe). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 2250). --spec transpose(list(list(ASD))) -> list(list(ASD)). -transpose(List_of_list) -> - Take_first = fun(List) -> case List of - [] -> - []; - - [F] -> - [F]; - - [F@1 | _] -> - [F@1] - end end, - case List_of_list of - [] -> - []; - - [[] | Rest] -> - transpose(Rest); - - Rows -> - Firsts = begin - _pipe = Rows, - _pipe@1 = map(_pipe, Take_first), - flatten(_pipe@1) - end, - Rest@1 = transpose( - map(Rows, fun(_capture) -> drop(_capture, 1) end) - ), - [Firsts | Rest@1] - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 2232). --spec interleave(list(list(ARZ))) -> list(ARZ). -interleave(List) -> - _pipe = transpose(List), - flatten(_pipe). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 2273). --spec do_shuffle_pair_unwrap(list({float(), ASI}), list(ASI)) -> list(ASI). -do_shuffle_pair_unwrap(List, Acc) -> - case List of - [] -> - Acc; - - [Elem_pair | Enumerable] -> - do_shuffle_pair_unwrap( - Enumerable, - [erlang:element(2, Elem_pair) | Acc] - ) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 2281). --spec do_shuffle_by_pair_indexes(list({float(), ASM})) -> list({float(), ASM}). -do_shuffle_by_pair_indexes(List_of_pairs) -> - sort( - List_of_pairs, - fun(A_pair, B_pair) -> - gleam@float:compare( - erlang:element(1, A_pair), - erlang:element(1, B_pair) - ) - end - ). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 2300). --spec shuffle(list(ASP)) -> list(ASP). -shuffle(List) -> - _pipe = List, - _pipe@1 = fold(_pipe, [], fun(Acc, A) -> [{rand:uniform(), A} | Acc] end), - _pipe@2 = do_shuffle_by_pair_indexes(_pipe@1), - do_shuffle_pair_unwrap(_pipe@2, []). diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@option.erl b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@option.erl deleted file mode 100644 index 9348cc1ec6b..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@option.erl +++ /dev/null @@ -1,162 +0,0 @@ --module(gleam@option). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([all/1, is_some/1, is_none/1, to_result/2, from_result/1, unwrap/2, lazy_unwrap/2, map/2, flatten/1, then/2, 'or'/2, lazy_or/2, values/1]). --export_type([option/1]). - --type option(FV) :: {some, FV} | none. - --file("/Users/louis/src/gleam/stdlib/src/gleam/option.gleam", 24). --spec do_all(list(option(FW)), list(FW)) -> option(list(FW)). -do_all(List, Acc) -> - case List of - [] -> - {some, Acc}; - - [X | Rest] -> - Accumulate = fun(Acc@1, Item) -> case {Acc@1, Item} of - {{some, Values}, {some, Value}} -> - {some, [Value | Values]}; - - {_, _} -> - none - end end, - Accumulate(do_all(Rest, Acc), X) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/option.gleam", 55). --spec all(list(option(GC))) -> option(list(GC)). -all(List) -> - do_all(List, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/option.gleam", 73). --spec is_some(option(any())) -> boolean(). -is_some(Option) -> - Option /= none. - --file("/Users/louis/src/gleam/stdlib/src/gleam/option.gleam", 91). --spec is_none(option(any())) -> boolean(). -is_none(Option) -> - Option =:= none. - --file("/Users/louis/src/gleam/stdlib/src/gleam/option.gleam", 109). --spec to_result(option(GL), GO) -> {ok, GL} | {error, GO}. -to_result(Option, E) -> - case Option of - {some, A} -> - {ok, A}; - - _ -> - {error, E} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/option.gleam", 130). --spec from_result({ok, GR} | {error, any()}) -> option(GR). -from_result(Result) -> - case Result of - {ok, A} -> - {some, A}; - - _ -> - none - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/option.gleam", 151). --spec unwrap(option(GW), GW) -> GW. -unwrap(Option, Default) -> - case Option of - {some, X} -> - X; - - none -> - Default - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/option.gleam", 172). --spec lazy_unwrap(option(GY), fun(() -> GY)) -> GY. -lazy_unwrap(Option, Default) -> - case Option of - {some, X} -> - X; - - none -> - Default() - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/option.gleam", 197). --spec map(option(HA), fun((HA) -> HC)) -> option(HC). -map(Option, Fun) -> - case Option of - {some, X} -> - {some, Fun(X)}; - - none -> - none - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/option.gleam", 223). --spec flatten(option(option(HE))) -> option(HE). -flatten(Option) -> - case Option of - {some, X} -> - X; - - none -> - none - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/option.gleam", 262). --spec then(option(HI), fun((HI) -> option(HK))) -> option(HK). -then(Option, Fun) -> - case Option of - {some, X} -> - Fun(X); - - none -> - none - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/option.gleam", 293). --spec 'or'(option(HN), option(HN)) -> option(HN). -'or'(First, Second) -> - case First of - {some, _} -> - First; - - none -> - Second - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/option.gleam", 324). --spec lazy_or(option(HR), fun(() -> option(HR))) -> option(HR). -lazy_or(First, Second) -> - case First of - {some, _} -> - First; - - none -> - Second() - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/option.gleam", 331). --spec do_values(list(option(HV)), list(HV)) -> list(HV). -do_values(List, Acc) -> - case List of - [] -> - Acc; - - [First | Rest] -> - Accumulate = fun(Acc@1, Item) -> case Item of - {some, Value} -> - [Value | Acc@1]; - - none -> - Acc@1 - end end, - Accumulate(do_values(Rest, Acc), First) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/option.gleam", 356). --spec values(list(option(IA))) -> list(IA). -values(Options) -> - do_values(Options, []). diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@order.erl b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@order.erl deleted file mode 100644 index 415ecc11fa8..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@order.erl +++ /dev/null @@ -1,85 +0,0 @@ --module(gleam@order). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([negate/1, to_int/1, compare/2, reverse/1, break_tie/2, lazy_break_tie/2]). --export_type([order/0]). - --type order() :: lt | eq | gt. - --file("/Users/louis/src/gleam/stdlib/src/gleam/order.gleam", 35). --spec negate(order()) -> order(). -negate(Order) -> - case Order of - lt -> - gt; - - eq -> - eq; - - gt -> - lt - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/order.gleam", 62). --spec to_int(order()) -> integer(). -to_int(Order) -> - case Order of - lt -> - -1; - - eq -> - 0; - - gt -> - 1 - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/order.gleam", 79). --spec compare(order(), order()) -> order(). -compare(A, B) -> - case {A, B} of - {X, Y} when X =:= Y -> - eq; - - {lt, _} -> - lt; - - {eq, gt} -> - lt; - - {_, _} -> - gt - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/order.gleam", 100). --spec reverse(fun((I, I) -> order())) -> fun((I, I) -> order()). -reverse(Orderer) -> - fun(A, B) -> Orderer(B, A) end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/order.gleam", 122). --spec break_tie(order(), order()) -> order(). -break_tie(Order, Other) -> - case Order of - lt -> - Order; - - gt -> - Order; - - eq -> - Other - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/order.gleam", 151). --spec lazy_break_tie(order(), fun(() -> order())) -> order(). -lazy_break_tie(Order, Comparison) -> - case Order of - lt -> - Order; - - gt -> - Order; - - eq -> - Comparison() - end. diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@pair.erl b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@pair.erl deleted file mode 100644 index 160cfb98f80..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@pair.erl +++ /dev/null @@ -1,39 +0,0 @@ --module(gleam@pair). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([first/1, second/1, swap/1, map_first/2, map_second/2, new/2]). - --file("/Users/louis/src/gleam/stdlib/src/gleam/pair.gleam", 10). --spec first({YZ, any()}) -> YZ. -first(Pair) -> - {A, _} = Pair, - A. - --file("/Users/louis/src/gleam/stdlib/src/gleam/pair.gleam", 24). --spec second({any(), AAC}) -> AAC. -second(Pair) -> - {_, A} = Pair, - A. - --file("/Users/louis/src/gleam/stdlib/src/gleam/pair.gleam", 38). --spec swap({AAD, AAE}) -> {AAE, AAD}. -swap(Pair) -> - {A, B} = Pair, - {B, A}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/pair.gleam", 53). --spec map_first({AAF, AAG}, fun((AAF) -> AAH)) -> {AAH, AAG}. -map_first(Pair, Fun) -> - {A, B} = Pair, - {Fun(A), B}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/pair.gleam", 68). --spec map_second({AAI, AAJ}, fun((AAJ) -> AAK)) -> {AAI, AAK}. -map_second(Pair, Fun) -> - {A, B} = Pair, - {A, Fun(B)}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/pair.gleam", 83). --spec new(AAL, AAM) -> {AAL, AAM}. -new(First, Second) -> - {First, Second}. diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@queue.erl b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@queue.erl deleted file mode 100644 index 10012632bf5..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@queue.erl +++ /dev/null @@ -1,134 +0,0 @@ --module(gleam@queue). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([new/0, from_list/1, to_list/1, is_empty/1, length/1, push_back/2, push_front/2, pop_back/1, pop_front/1, reverse/1, is_logically_equal/3, is_equal/2]). --export_type([queue/1]). - --opaque queue(EXK) :: {queue, list(EXK), list(EXK)}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/queue.gleam", 22). --spec new() -> queue(any()). -new() -> - {queue, [], []}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/queue.gleam", 38). --spec from_list(list(EXN)) -> queue(EXN). -from_list(List) -> - {queue, [], List}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/queue.gleam", 54). --spec to_list(queue(EXQ)) -> list(EXQ). -to_list(Queue) -> - _pipe = erlang:element(3, Queue), - lists:append(_pipe, lists:reverse(erlang:element(2, Queue))). - --file("/Users/louis/src/gleam/stdlib/src/gleam/queue.gleam", 80). --spec is_empty(queue(any())) -> boolean(). -is_empty(Queue) -> - (erlang:element(2, Queue) =:= []) andalso (erlang:element(3, Queue) =:= []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/queue.gleam", 106). --spec length(queue(any())) -> integer(). -length(Queue) -> - erlang:length(erlang:element(2, Queue)) + erlang:length( - erlang:element(3, Queue) - ). - --file("/Users/louis/src/gleam/stdlib/src/gleam/queue.gleam", 119). --spec push_back(queue(EXX), EXX) -> queue(EXX). -push_back(Queue, Item) -> - {queue, [Item | erlang:element(2, Queue)], erlang:element(3, Queue)}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/queue.gleam", 132). --spec push_front(queue(EYA), EYA) -> queue(EYA). -push_front(Queue, Item) -> - {queue, erlang:element(2, Queue), [Item | erlang:element(3, Queue)]}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/queue.gleam", 164). --spec pop_back(queue(EYD)) -> {ok, {EYD, queue(EYD)}} | {error, nil}. -pop_back(Queue) -> - case Queue of - {queue, [], []} -> - {error, nil}; - - {queue, [], Out} -> - pop_back({queue, lists:reverse(Out), []}); - - {queue, [First | Rest], Out@1} -> - Queue@1 = {queue, Rest, Out@1}, - {ok, {First, Queue@1}} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/queue.gleam", 203). --spec pop_front(queue(EYI)) -> {ok, {EYI, queue(EYI)}} | {error, nil}. -pop_front(Queue) -> - case Queue of - {queue, [], []} -> - {error, nil}; - - {queue, In, []} -> - pop_front({queue, [], lists:reverse(In)}); - - {queue, In@1, [First | Rest]} -> - Queue@1 = {queue, In@1, Rest}, - {ok, {First, Queue@1}} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/queue.gleam", 236). --spec reverse(queue(EYN)) -> queue(EYN). -reverse(Queue) -> - {queue, erlang:element(3, Queue), erlang:element(2, Queue)}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/queue.gleam", 240). --spec check_equal( - list(EYQ), - list(EYQ), - list(EYQ), - list(EYQ), - fun((EYQ, EYQ) -> boolean()) -) -> boolean(). -check_equal(Xs, X_tail, Ys, Y_tail, Eq) -> - case {Xs, X_tail, Ys, Y_tail} of - {[], [], [], []} -> - true; - - {[X | Xs@1], _, [Y | Ys@1], _} -> - case Eq(X, Y) of - false -> - false; - - true -> - check_equal(Xs@1, X_tail, Ys@1, Y_tail, Eq) - end; - - {[], [_ | _], _, _} -> - check_equal(lists:reverse(X_tail), [], Ys, Y_tail, Eq); - - {_, _, [], [_ | _]} -> - check_equal(Xs, X_tail, lists:reverse(Y_tail), [], Eq); - - {_, _, _, _} -> - false - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/queue.gleam", 271). --spec is_logically_equal(queue(EYV), queue(EYV), fun((EYV, EYV) -> boolean())) -> boolean(). -is_logically_equal(A, B, Element_is_equal) -> - check_equal( - erlang:element(3, A), - erlang:element(2, A), - erlang:element(3, B), - erlang:element(2, B), - Element_is_equal - ). - --file("/Users/louis/src/gleam/stdlib/src/gleam/queue.gleam", 288). --spec is_equal(queue(EYY), queue(EYY)) -> boolean(). -is_equal(A, B) -> - check_equal( - erlang:element(3, A), - erlang:element(2, A), - erlang:element(3, B), - erlang:element(2, B), - fun(A@1, B@1) -> A@1 =:= B@1 end - ). diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@regex.erl b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@regex.erl deleted file mode 100644 index d3f32160afd..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@regex.erl +++ /dev/null @@ -1,43 +0,0 @@ --module(gleam@regex). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([compile/2, from_string/1, check/2, split/2, scan/2, replace/3]). --export_type([regex/0, match/0, compile_error/0, options/0]). - --type regex() :: any(). - --type match() :: {match, binary(), list(gleam@option:option(binary()))}. - --type compile_error() :: {compile_error, binary(), integer()}. - --type options() :: {options, boolean(), boolean()}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/regex.gleam", 55). --spec compile(binary(), options()) -> {ok, regex()} | {error, compile_error()}. -compile(Pattern, Options) -> - gleam_stdlib:compile_regex(Pattern, Options). - --file("/Users/louis/src/gleam/stdlib/src/gleam/regex.gleam", 92). --spec from_string(binary()) -> {ok, regex()} | {error, compile_error()}. -from_string(Pattern) -> - compile(Pattern, {options, false, false}). - --file("/Users/louis/src/gleam/stdlib/src/gleam/regex.gleam", 111). --spec check(regex(), binary()) -> boolean(). -check(Regex, String) -> - gleam_stdlib:regex_check(Regex, String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/regex.gleam", 129). --spec split(regex(), binary()) -> list(binary()). -split(Regex, String) -> - gleam_stdlib:regex_split(Regex, String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/regex.gleam", 189). --spec scan(regex(), binary()) -> list(match()). -scan(Regex, String) -> - gleam_stdlib:regex_scan(Regex, String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/regex.gleam", 215). --spec replace(regex(), binary(), binary()) -> binary(). -replace(Pattern, String, Substitute) -> - gleam_stdlib:regex_replace(Pattern, String, Substitute). diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@result.erl b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@result.erl deleted file mode 100644 index cfe30f62f9c..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@result.erl +++ /dev/null @@ -1,222 +0,0 @@ --module(gleam@result). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([is_ok/1, is_error/1, map/2, map_error/2, flatten/1, 'try'/2, then/2, unwrap/2, lazy_unwrap/2, unwrap_error/2, unwrap_both/1, nil_error/1, 'or'/2, lazy_or/2, all/1, partition/1, replace/2, replace_error/2, values/1, try_recover/2]). - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 20). --spec is_ok({ok, any()} | {error, any()}) -> boolean(). -is_ok(Result) -> - case Result of - {error, _} -> - false; - - {ok, _} -> - true - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 41). --spec is_error({ok, any()} | {error, any()}) -> boolean(). -is_error(Result) -> - case Result of - {ok, _} -> - false; - - {error, _} -> - true - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 66). --spec map({ok, BXE} | {error, BXF}, fun((BXE) -> BXI)) -> {ok, BXI} | - {error, BXF}. -map(Result, Fun) -> - case Result of - {ok, X} -> - {ok, Fun(X)}; - - {error, E} -> - {error, E} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 91). --spec map_error({ok, BXL} | {error, BXM}, fun((BXM) -> BXP)) -> {ok, BXL} | - {error, BXP}. -map_error(Result, Fun) -> - case Result of - {ok, X} -> - {ok, X}; - - {error, Error} -> - {error, Fun(Error)} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 120). --spec flatten({ok, {ok, BXS} | {error, BXT}} | {error, BXT}) -> {ok, BXS} | - {error, BXT}. -flatten(Result) -> - case Result of - {ok, X} -> - X; - - {error, Error} -> - {error, Error} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 158). --spec 'try'({ok, BYA} | {error, BYB}, fun((BYA) -> {ok, BYE} | {error, BYB})) -> {ok, - BYE} | - {error, BYB}. -'try'(Result, Fun) -> - case Result of - {ok, X} -> - Fun(X); - - {error, E} -> - {error, E} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 170). --spec then({ok, BYJ} | {error, BYK}, fun((BYJ) -> {ok, BYN} | {error, BYK})) -> {ok, - BYN} | - {error, BYK}. -then(Result, Fun) -> - 'try'(Result, Fun). - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 192). --spec unwrap({ok, BYS} | {error, any()}, BYS) -> BYS. -unwrap(Result, Default) -> - case Result of - {ok, V} -> - V; - - {error, _} -> - Default - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 214). --spec lazy_unwrap({ok, BYW} | {error, any()}, fun(() -> BYW)) -> BYW. -lazy_unwrap(Result, Default) -> - case Result of - {ok, V} -> - V; - - {error, _} -> - Default() - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 236). --spec unwrap_error({ok, any()} | {error, BZB}, BZB) -> BZB. -unwrap_error(Result, Default) -> - case Result of - {ok, _} -> - Default; - - {error, E} -> - E - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 258). --spec unwrap_both({ok, BZE} | {error, BZE}) -> BZE. -unwrap_both(Result) -> - case Result of - {ok, A} -> - A; - - {error, A@1} -> - A@1 - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 279). --spec nil_error({ok, BZH} | {error, any()}) -> {ok, BZH} | {error, nil}. -nil_error(Result) -> - map_error(Result, fun(_) -> nil end). - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 307). --spec 'or'({ok, BZN} | {error, BZO}, {ok, BZN} | {error, BZO}) -> {ok, BZN} | - {error, BZO}. -'or'(First, Second) -> - case First of - {ok, _} -> - First; - - {error, _} -> - Second - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 340). --spec lazy_or({ok, BZV} | {error, BZW}, fun(() -> {ok, BZV} | {error, BZW})) -> {ok, - BZV} | - {error, BZW}. -lazy_or(First, Second) -> - case First of - {ok, _} -> - First; - - {error, _} -> - Second() - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 366). --spec all(list({ok, CAD} | {error, CAE})) -> {ok, list(CAD)} | {error, CAE}. -all(Results) -> - gleam@list:try_map(Results, fun(X) -> X end). - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 386). --spec do_partition(list({ok, CAS} | {error, CAT}), list(CAS), list(CAT)) -> {list(CAS), - list(CAT)}. -do_partition(Results, Oks, Errors) -> - case Results of - [] -> - {Oks, Errors}; - - [{ok, A} | Rest] -> - do_partition(Rest, [A | Oks], Errors); - - [{error, E} | Rest@1] -> - do_partition(Rest@1, Oks, [E | Errors]) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 382). --spec partition(list({ok, CAL} | {error, CAM})) -> {list(CAL), list(CAM)}. -partition(Results) -> - do_partition(Results, [], []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 408). --spec replace({ok, any()} | {error, CBB}, CBE) -> {ok, CBE} | {error, CBB}. -replace(Result, Value) -> - case Result of - {ok, _} -> - {ok, Value}; - - {error, Error} -> - {error, Error} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 429). --spec replace_error({ok, CBH} | {error, any()}, CBL) -> {ok, CBH} | {error, CBL}. -replace_error(Result, Error) -> - case Result of - {ok, X} -> - {ok, X}; - - {error, _} -> - {error, Error} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 445). --spec values(list({ok, CBO} | {error, any()})) -> list(CBO). -values(Results) -> - gleam@list:filter_map(Results, fun(R) -> R end). - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 478). --spec try_recover( - {ok, CBU} | {error, CBV}, - fun((CBV) -> {ok, CBU} | {error, CBY}) -) -> {ok, CBU} | {error, CBY}. -try_recover(Result, Fun) -> - case Result of - {ok, Value} -> - {ok, Value}; - - {error, Error} -> - Fun(Error) - end. diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@set.erl b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@set.erl deleted file mode 100644 index 5aef9f27ec9..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@set.erl +++ /dev/null @@ -1,141 +0,0 @@ --module(gleam@set). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([new/0, size/1, is_empty/1, contains/2, delete/2, to_list/1, fold/3, filter/2, drop/2, take/2, intersection/2, difference/2, is_subset/2, is_disjoint/2, each/2, insert/2, from_list/1, map/2, union/2, symmetric_difference/2]). --export_type([set/1]). - --opaque set(FCW) :: {set, gleam@dict:dict(FCW, list(nil))}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 32). --spec new() -> set(any()). -new() -> - {set, gleam@dict:new()}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 50). --spec size(set(any())) -> integer(). -size(Set) -> - maps:size(erlang:element(2, Set)). - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 68). --spec is_empty(set(any())) -> boolean(). -is_empty(Set) -> - Set =:= new(). - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 110). --spec contains(set(FDH), FDH) -> boolean(). -contains(Set, Member) -> - _pipe = erlang:element(2, Set), - _pipe@1 = gleam@dict:get(_pipe, Member), - gleam@result:is_ok(_pipe@1). - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 131). --spec delete(set(FDJ), FDJ) -> set(FDJ). -delete(Set, Member) -> - {set, gleam@dict:delete(erlang:element(2, Set), Member)}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 149). --spec to_list(set(FDM)) -> list(FDM). -to_list(Set) -> - gleam@dict:keys(erlang:element(2, Set)). - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 190). --spec fold(set(FDS), FDU, fun((FDU, FDS) -> FDU)) -> FDU. -fold(Set, Initial, Reducer) -> - gleam@dict:fold( - erlang:element(2, Set), - Initial, - fun(A, K, _) -> Reducer(A, K) end - ). - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 214). --spec filter(set(FDV), fun((FDV) -> boolean())) -> set(FDV). -filter(Set, Predicate) -> - {set, - gleam@dict:filter(erlang:element(2, Set), fun(M, _) -> Predicate(M) end)}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 249). --spec drop(set(FEC), list(FEC)) -> set(FEC). -drop(Set, Disallowed) -> - gleam@list:fold(Disallowed, Set, fun delete/2). - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 267). --spec take(set(FEG), list(FEG)) -> set(FEG). -take(Set, Desired) -> - {set, gleam@dict:take(erlang:element(2, Set), Desired)}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 271). --spec order(set(FEK), set(FEK)) -> {set(FEK), set(FEK)}. -order(First, Second) -> - case maps:size(erlang:element(2, First)) > maps:size( - erlang:element(2, Second) - ) of - true -> - {First, Second}; - - false -> - {Second, First} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 305). --spec intersection(set(FET), set(FET)) -> set(FET). -intersection(First, Second) -> - {Larger, Smaller} = order(First, Second), - take(Larger, to_list(Smaller)). - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 323). --spec difference(set(FEX), set(FEX)) -> set(FEX). -difference(First, Second) -> - drop(First, to_list(Second)). - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 344). --spec is_subset(set(FFB), set(FFB)) -> boolean(). -is_subset(First, Second) -> - intersection(First, Second) =:= First. - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 362). --spec is_disjoint(set(FFE), set(FFE)) -> boolean(). -is_disjoint(First, Second) -> - intersection(First, Second) =:= new(). - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 402). --spec each(set(FFL), fun((FFL) -> any())) -> nil. -each(Set, Fun) -> - fold( - Set, - nil, - fun(Nil, Member) -> - Fun(Member), - Nil - end - ). - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 86). --spec insert(set(FDE), FDE) -> set(FDE). -insert(Set, Member) -> - {set, gleam@dict:insert(erlang:element(2, Set), Member, [])}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 167). --spec from_list(list(FDP)) -> set(FDP). -from_list(Members) -> - Dict = gleam@list:fold( - Members, - gleam@dict:new(), - fun(M, K) -> gleam@dict:insert(M, K, []) end - ), - {set, Dict}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 232). --spec map(set(FDY), fun((FDY) -> FEA)) -> set(FEA). -map(Set, Fun) -> - fold(Set, new(), fun(Acc, Member) -> insert(Acc, Fun(Member)) end). - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 289). --spec union(set(FEP), set(FEP)) -> set(FEP). -union(First, Second) -> - {Larger, Smaller} = order(First, Second), - fold(Smaller, Larger, fun insert/2). - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 374). --spec symmetric_difference(set(FFH), set(FFH)) -> set(FFH). -symmetric_difference(First, Second) -> - difference(union(First, Second), intersection(First, Second)). diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@string.erl b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@string.erl deleted file mode 100644 index f7a2ff89742..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@string.erl +++ /dev/null @@ -1,409 +0,0 @@ --module(gleam@string). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([is_empty/1, length/1, reverse/1, replace/3, lowercase/1, uppercase/1, compare/2, slice/3, crop/2, drop_left/2, drop_right/2, contains/2, starts_with/2, ends_with/2, split_once/2, append/2, concat/1, repeat/2, join/2, pad_left/3, pad_right/3, trim/1, trim_left/1, trim_right/1, pop_grapheme/1, to_graphemes/1, split/2, to_utf_codepoints/1, from_utf_codepoints/1, utf_codepoint/1, utf_codepoint_to_int/1, to_option/1, first/1, last/1, capitalise/1, inspect/1, byte_size/1]). --export_type([direction/0]). - --type direction() :: leading | trailing | both. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 23). --spec is_empty(binary()) -> boolean(). -is_empty(Str) -> - Str =:= <<""/utf8>>. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 49). --spec length(binary()) -> integer(). -length(String) -> - string:length(String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 73). --spec do_reverse(binary()) -> binary(). -do_reverse(String) -> - _pipe = String, - _pipe@1 = gleam@string_builder:from_string(_pipe), - _pipe@2 = gleam@string_builder:reverse(_pipe@1), - gleam@string_builder:to_string(_pipe@2). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 69). --spec reverse(binary()) -> binary(). -reverse(String) -> - do_reverse(String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 94). --spec replace(binary(), binary(), binary()) -> binary(). -replace(String, Pattern, Substitute) -> - _pipe = String, - _pipe@1 = gleam@string_builder:from_string(_pipe), - _pipe@2 = gleam_stdlib:string_replace(_pipe@1, Pattern, Substitute), - gleam@string_builder:to_string(_pipe@2). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 117). --spec lowercase(binary()) -> binary(). -lowercase(String) -> - string:lowercase(String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 137). --spec uppercase(binary()) -> binary(). -uppercase(String) -> - string:uppercase(String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 161). --spec compare(binary(), binary()) -> gleam@order:order(). -compare(A, B) -> - case A =:= B of - true -> - eq; - - _ -> - case gleam_stdlib:less_than(A, B) of - true -> - lt; - - _ -> - gt - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 206). --spec slice(binary(), integer(), integer()) -> binary(). -slice(String, Idx, Len) -> - case Len < 0 of - true -> - <<""/utf8>>; - - false -> - case Idx < 0 of - true -> - Translated_idx = length(String) + Idx, - case Translated_idx < 0 of - true -> - <<""/utf8>>; - - false -> - gleam_stdlib:slice(String, Translated_idx, Len) - end; - - false -> - gleam_stdlib:slice(String, Idx, Len) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 239). --spec crop(binary(), binary()) -> binary(). -crop(String, Substring) -> - gleam_stdlib:crop_string(String, Substring). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 250). --spec drop_left(binary(), integer()) -> binary(). -drop_left(String, Num_graphemes) -> - case Num_graphemes < 0 of - true -> - String; - - false -> - slice(String, Num_graphemes, length(String) - Num_graphemes) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 266). --spec drop_right(binary(), integer()) -> binary(). -drop_right(String, Num_graphemes) -> - case Num_graphemes < 0 of - true -> - String; - - false -> - slice(String, 0, length(String) - Num_graphemes) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 294). --spec contains(binary(), binary()) -> boolean(). -contains(Haystack, Needle) -> - gleam_stdlib:contains_string(Haystack, Needle). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 305). --spec starts_with(binary(), binary()) -> boolean(). -starts_with(String, Prefix) -> - gleam_stdlib:string_starts_with(String, Prefix). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 322). --spec ends_with(binary(), binary()) -> boolean(). -ends_with(String, Suffix) -> - gleam_stdlib:string_ends_with(String, Suffix). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 374). --spec do_split_once(binary(), binary()) -> {ok, {binary(), binary()}} | - {error, nil}. -do_split_once(String, Substring) -> - case string:split(String, Substring) of - [First, Rest] -> - {ok, {First, Rest}}; - - _ -> - {error, nil} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 366). --spec split_once(binary(), binary()) -> {ok, {binary(), binary()}} | - {error, nil}. -split_once(String, Substring) -> - do_split_once(String, Substring). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 400). --spec append(binary(), binary()) -> binary(). -append(First, Second) -> - _pipe = First, - _pipe@1 = gleam@string_builder:from_string(_pipe), - _pipe@2 = gleam@string_builder:append(_pipe@1, Second), - gleam@string_builder:to_string(_pipe@2). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 420). --spec concat(list(binary())) -> binary(). -concat(Strings) -> - _pipe = Strings, - _pipe@1 = gleam@string_builder:from_strings(_pipe), - gleam@string_builder:to_string(_pipe@1). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 441). --spec do_repeat(binary(), integer(), binary()) -> binary(). -do_repeat(String, Times, Acc) -> - case Times =< 0 of - true -> - Acc; - - false -> - do_repeat(String, Times - 1, <>) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 437). --spec repeat(binary(), integer()) -> binary(). -repeat(String, Times) -> - do_repeat(String, Times, <<""/utf8>>). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 464). --spec do_join(list(binary()), binary()) -> binary(). -do_join(Strings, Separator) -> - _pipe = Strings, - _pipe@1 = gleam@list:intersperse(_pipe, Separator), - concat(_pipe@1). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 459). --spec join(list(binary()), binary()) -> binary(). -join(Strings, Separator) -> - do_join(Strings, Separator). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 536). --spec padding(integer(), binary()) -> binary(). -padding(Size, Pad_string) -> - Pad_string_length = length(Pad_string), - Num_pads = case Pad_string_length of - 0 -> 0; - Gleam@denominator -> Size div Gleam@denominator - end, - Extra = case Pad_string_length of - 0 -> 0; - Gleam@denominator@1 -> Size rem Gleam@denominator@1 - end, - <<(repeat(Pad_string, Num_pads))/binary, - (slice(Pad_string, 0, Extra))/binary>>. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 489). --spec pad_left(binary(), integer(), binary()) -> binary(). -pad_left(String, Desired_length, Pad_string) -> - Current_length = length(String), - To_pad_length = Desired_length - Current_length, - case To_pad_length =< 0 of - true -> - String; - - false -> - <<(padding(To_pad_length, Pad_string))/binary, String/binary>> - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 522). --spec pad_right(binary(), integer(), binary()) -> binary(). -pad_right(String, Desired_length, Pad_string) -> - Current_length = length(String), - To_pad_length = Desired_length - Current_length, - case To_pad_length =< 0 of - true -> - String; - - false -> - <> - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 558). --spec do_trim(binary()) -> binary(). -do_trim(String) -> - string:trim(String, both). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 553). --spec trim(binary()) -> binary(). -trim(String) -> - do_trim(String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 585). --spec do_trim_left(binary()) -> binary(). -do_trim_left(String) -> - string:trim(String, leading). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 580). --spec trim_left(binary()) -> binary(). -trim_left(String) -> - do_trim_left(String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 603). --spec do_trim_right(binary()) -> binary(). -do_trim_right(String) -> - string:trim(String, trailing). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 598). --spec trim_right(binary()) -> binary(). -trim_right(String) -> - do_trim_right(String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 626). --spec pop_grapheme(binary()) -> {ok, {binary(), binary()}} | {error, nil}. -pop_grapheme(String) -> - gleam_stdlib:string_pop_grapheme(String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 648). --spec do_to_graphemes(binary(), list(binary())) -> list(binary()). -do_to_graphemes(String, Acc) -> - case pop_grapheme(String) of - {ok, {Grapheme, Rest}} -> - do_to_graphemes(Rest, [Grapheme | Acc]); - - _ -> - Acc - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 643). --spec to_graphemes(binary()) -> list(binary()). -to_graphemes(String) -> - _pipe = do_to_graphemes(String, []), - lists:reverse(_pipe). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 339). --spec split(binary(), binary()) -> list(binary()). -split(X, Substring) -> - case Substring of - <<""/utf8>> -> - to_graphemes(X); - - _ -> - _pipe = X, - _pipe@1 = gleam@string_builder:from_string(_pipe), - _pipe@2 = gleam@string_builder:split(_pipe@1, Substring), - gleam@list:map(_pipe@2, fun gleam@string_builder:to_string/1) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 696). --spec do_to_utf_codepoints_impl(bitstring(), list(integer())) -> list(integer()). -do_to_utf_codepoints_impl(Bit_array, Acc) -> - case Bit_array of - <> -> - do_to_utf_codepoints_impl(Rest, [First | Acc]); - - _ -> - Acc - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 690). --spec do_to_utf_codepoints(binary()) -> list(integer()). -do_to_utf_codepoints(String) -> - _pipe = do_to_utf_codepoints_impl(<>, []), - lists:reverse(_pipe). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 685). --spec to_utf_codepoints(binary()) -> list(integer()). -to_utf_codepoints(String) -> - do_to_utf_codepoints(String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 736). --spec from_utf_codepoints(list(integer())) -> binary(). -from_utf_codepoints(Utf_codepoints) -> - gleam_stdlib:utf_codepoint_list_to_string(Utf_codepoints). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 742). --spec utf_codepoint(integer()) -> {ok, integer()} | {error, nil}. -utf_codepoint(Value) -> - case Value of - I when I > 1114111 -> - {error, nil}; - - 65534 -> - {error, nil}; - - 65535 -> - {error, nil}; - - I@1 when (I@1 >= 55296) andalso (I@1 =< 57343) -> - {error, nil}; - - I@2 -> - {ok, gleam_stdlib:identity(I@2)} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 761). --spec utf_codepoint_to_int(integer()) -> integer(). -utf_codepoint_to_int(Cp) -> - gleam_stdlib:identity(Cp). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 784). --spec to_option(binary()) -> gleam@option:option(binary()). -to_option(String) -> - case String of - <<""/utf8>> -> - none; - - _ -> - {some, String} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 807). --spec first(binary()) -> {ok, binary()} | {error, nil}. -first(String) -> - case pop_grapheme(String) of - {ok, {First, _}} -> - {ok, First}; - - {error, E} -> - {error, E} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 830). --spec last(binary()) -> {ok, binary()} | {error, nil}. -last(String) -> - case pop_grapheme(String) of - {ok, {First, <<""/utf8>>}} -> - {ok, First}; - - {ok, {_, Rest}} -> - {ok, slice(Rest, -1, 1)}; - - {error, E} -> - {error, E} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 848). --spec capitalise(binary()) -> binary(). -capitalise(String) -> - case pop_grapheme(String) of - {ok, {First, Rest}} -> - append(uppercase(First), lowercase(Rest)); - - _ -> - <<""/utf8>> - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 857). --spec inspect(any()) -> binary(). -inspect(Term) -> - _pipe = gleam_stdlib:inspect(Term), - gleam@string_builder:to_string(_pipe). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 880). --spec byte_size(binary()) -> integer(). -byte_size(String) -> - erlang:byte_size(String). diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@string_builder.erl b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@string_builder.erl deleted file mode 100644 index ce421cb8520..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@string_builder.erl +++ /dev/null @@ -1,106 +0,0 @@ --module(gleam@string_builder). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([prepend_builder/2, append_builder/2, new/0, from_strings/1, concat/1, from_string/1, prepend/2, append/2, to_string/1, byte_size/1, join/2, lowercase/1, uppercase/1, reverse/1, split/2, replace/3, is_equal/2, is_empty/1]). --export_type([string_builder/0, direction/0]). - --type string_builder() :: any(). - --type direction() :: all. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 51). --spec prepend_builder(string_builder(), string_builder()) -> string_builder(). -prepend_builder(Builder, Prefix) -> - gleam_stdlib:iodata_append(Prefix, Builder). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 62). --spec append_builder(string_builder(), string_builder()) -> string_builder(). -append_builder(Builder, Suffix) -> - gleam_stdlib:iodata_append(Builder, Suffix). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 24). --spec new() -> string_builder(). -new() -> - gleam_stdlib:identity([]). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 77). --spec from_strings(list(binary())) -> string_builder(). -from_strings(Strings) -> - gleam_stdlib:identity(Strings). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 89). --spec concat(list(string_builder())) -> string_builder(). -concat(Builders) -> - gleam_stdlib:identity(Builders). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 101). --spec from_string(binary()) -> string_builder(). -from_string(String) -> - gleam_stdlib:identity(String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 32). --spec prepend(string_builder(), binary()) -> string_builder(). -prepend(Builder, Prefix) -> - append_builder(from_string(Prefix), Builder). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 43). --spec append(string_builder(), binary()) -> string_builder(). -append(Builder, Second) -> - append_builder(Builder, from_string(Second)). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 114). --spec to_string(string_builder()) -> binary(). -to_string(Builder) -> - unicode:characters_to_binary(Builder). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 124). --spec byte_size(string_builder()) -> integer(). -byte_size(Builder) -> - erlang:iolist_size(Builder). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 134). --spec join(list(string_builder()), binary()) -> string_builder(). -join(Builders, Sep) -> - _pipe = Builders, - _pipe@1 = gleam@list:intersperse(_pipe, from_string(Sep)), - concat(_pipe@1). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 143). --spec lowercase(string_builder()) -> string_builder(). -lowercase(Builder) -> - string:lowercase(Builder). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 154). --spec uppercase(string_builder()) -> string_builder(). -uppercase(Builder) -> - string:uppercase(Builder). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 164). --spec reverse(string_builder()) -> string_builder(). -reverse(Builder) -> - string:reverse(Builder). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 191). --spec do_split(string_builder(), binary()) -> list(string_builder()). -do_split(Iodata, Pattern) -> - string:split(Iodata, Pattern, all). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 182). --spec split(string_builder(), binary()) -> list(string_builder()). -split(Iodata, Pattern) -> - do_split(Iodata, Pattern). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 202). --spec replace(string_builder(), binary(), binary()) -> string_builder(). -replace(Builder, Pattern, Substitute) -> - gleam_stdlib:string_replace(Builder, Pattern, Substitute). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 227). --spec is_equal(string_builder(), string_builder()) -> boolean(). -is_equal(A, B) -> - string:equal(A, B). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 251). --spec is_empty(string_builder()) -> boolean(). -is_empty(Builder) -> - string:is_empty(Builder). diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@uri.erl b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@uri.erl deleted file mode 100644 index b6d300f5616..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam@uri.erl +++ /dev/null @@ -1,376 +0,0 @@ --module(gleam@uri). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([parse/1, parse_query/1, percent_encode/1, query_to_string/1, percent_decode/1, path_segments/1, to_string/1, origin/1, merge/2]). --export_type([uri/0]). - --type uri() :: {uri, - gleam@option:option(binary()), - gleam@option:option(binary()), - gleam@option:option(binary()), - gleam@option:option(integer()), - binary(), - gleam@option:option(binary()), - gleam@option:option(binary())}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 116). --spec regex_submatches(binary(), binary()) -> list(gleam@option:option(binary())). -regex_submatches(Pattern, String) -> - _pipe = Pattern, - _pipe@1 = gleam@regex:compile(_pipe, {options, true, false}), - _pipe@2 = gleam@result:nil_error(_pipe@1), - _pipe@3 = gleam@result:map( - _pipe@2, - fun(_capture) -> gleam@regex:scan(_capture, String) end - ), - _pipe@4 = gleam@result:'try'(_pipe@3, fun gleam@list:first/1), - _pipe@5 = gleam@result:map(_pipe@4, fun(M) -> erlang:element(3, M) end), - gleam@result:unwrap(_pipe@5, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 126). --spec noneify_query(gleam@option:option(binary())) -> gleam@option:option(binary()). -noneify_query(X) -> - case X of - none -> - none; - - {some, X@1} -> - case gleam@string:pop_grapheme(X@1) of - {ok, {<<"?"/utf8>>, Query}} -> - {some, Query}; - - _ -> - none - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 137). --spec noneify_empty_string(gleam@option:option(binary())) -> gleam@option:option(binary()). -noneify_empty_string(X) -> - case X of - {some, <<""/utf8>>} -> - none; - - none -> - none; - - {some, _} -> - X - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 178). --spec extra_required(list(any()), integer()) -> integer(). -extra_required(List, Remaining) -> - case List of - _ when Remaining =:= 0 -> - 0; - - [] -> - Remaining; - - [_ | Rest] -> - extra_required(Rest, Remaining - 1) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 173). --spec pad_list(list(gleam@option:option(FJT)), integer()) -> list(gleam@option:option(FJT)). -pad_list(List, Size) -> - _pipe = List, - lists:append(_pipe, gleam@list:repeat(none, extra_required(List, Size))). - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 145). --spec split_authority(gleam@option:option(binary())) -> {gleam@option:option(binary()), - gleam@option:option(binary()), - gleam@option:option(integer())}. -split_authority(Authority) -> - case gleam@option:unwrap(Authority, <<""/utf8>>) of - <<""/utf8>> -> - {none, none, none}; - - <<"//"/utf8>> -> - {none, {some, <<""/utf8>>}, none}; - - Authority@1 -> - Matches = begin - _pipe = <<"^(//)?((.*)@)?(\\[[a-zA-Z0-9:.]*\\]|[^:]*)(:(\\d*))?"/utf8>>, - _pipe@1 = regex_submatches(_pipe, Authority@1), - pad_list(_pipe@1, 6) - end, - case Matches of - [_, _, Userinfo, Host, _, Port] -> - Userinfo@1 = noneify_empty_string(Userinfo), - Host@1 = noneify_empty_string(Host), - Port@1 = begin - _pipe@2 = Port, - _pipe@3 = gleam@option:unwrap(_pipe@2, <<""/utf8>>), - _pipe@4 = gleam@int:parse(_pipe@3), - gleam@option:from_result(_pipe@4) - end, - {Userinfo@1, Host@1, Port@1}; - - _ -> - {none, none, none} - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 56). --spec parse(binary()) -> {ok, uri()} | {error, nil}. -parse(Uri_string) -> - gleam_stdlib:uri_parse(Uri_string). - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 198). --spec parse_query(binary()) -> {ok, list({binary(), binary()})} | {error, nil}. -parse_query(Query) -> - gleam_stdlib:parse_query(Query). - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 242). --spec percent_encode(binary()) -> binary(). -percent_encode(Value) -> - gleam_stdlib:percent_encode(Value). - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 225). --spec query_pair({binary(), binary()}) -> gleam@string_builder:string_builder(). -query_pair(Pair) -> - gleam@string_builder:from_strings( - [percent_encode(erlang:element(1, Pair)), - <<"="/utf8>>, - percent_encode(erlang:element(2, Pair))] - ). - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 217). --spec query_to_string(list({binary(), binary()})) -> binary(). -query_to_string(Query) -> - _pipe = Query, - _pipe@1 = gleam@list:map(_pipe, fun query_pair/1), - _pipe@2 = gleam@list:intersperse( - _pipe@1, - gleam@string_builder:from_string(<<"&"/utf8>>) - ), - _pipe@3 = gleam@string_builder:concat(_pipe@2), - gleam@string_builder:to_string(_pipe@3). - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 259). --spec percent_decode(binary()) -> {ok, binary()} | {error, nil}. -percent_decode(Value) -> - gleam_stdlib:percent_decode(Value). - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 267). --spec do_remove_dot_segments(list(binary()), list(binary())) -> list(binary()). -do_remove_dot_segments(Input, Accumulator) -> - case Input of - [] -> - lists:reverse(Accumulator); - - [Segment | Rest] -> - Accumulator@5 = case {Segment, Accumulator} of - {<<""/utf8>>, Accumulator@1} -> - Accumulator@1; - - {<<"."/utf8>>, Accumulator@2} -> - Accumulator@2; - - {<<".."/utf8>>, []} -> - []; - - {<<".."/utf8>>, [_ | Accumulator@3]} -> - Accumulator@3; - - {Segment@1, Accumulator@4} -> - [Segment@1 | Accumulator@4] - end, - do_remove_dot_segments(Rest, Accumulator@5) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 286). --spec remove_dot_segments(list(binary())) -> list(binary()). -remove_dot_segments(Input) -> - do_remove_dot_segments(Input, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 302). --spec path_segments(binary()) -> list(binary()). -path_segments(Path) -> - remove_dot_segments(gleam@string:split(Path, <<"/"/utf8>>)). - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 318). --spec to_string(uri()) -> binary(). -to_string(Uri) -> - Parts = case erlang:element(8, Uri) of - {some, Fragment} -> - [<<"#"/utf8>>, Fragment]; - - _ -> - [] - end, - Parts@1 = case erlang:element(7, Uri) of - {some, Query} -> - [<<"?"/utf8>>, Query | Parts]; - - _ -> - Parts - end, - Parts@2 = [erlang:element(6, Uri) | Parts@1], - Parts@3 = case {erlang:element(4, Uri), - gleam@string:starts_with(erlang:element(6, Uri), <<"/"/utf8>>)} of - {{some, Host}, false} when Host =/= <<""/utf8>> -> - [<<"/"/utf8>> | Parts@2]; - - {_, _} -> - Parts@2 - end, - Parts@4 = case {erlang:element(4, Uri), erlang:element(5, Uri)} of - {{some, _}, {some, Port}} -> - [<<":"/utf8>>, gleam@int:to_string(Port) | Parts@3]; - - {_, _} -> - Parts@3 - end, - Parts@5 = case {erlang:element(2, Uri), - erlang:element(3, Uri), - erlang:element(4, Uri)} of - {{some, S}, {some, U}, {some, H}} -> - [S, <<"://"/utf8>>, U, <<"@"/utf8>>, H | Parts@4]; - - {{some, S@1}, none, {some, H@1}} -> - [S@1, <<"://"/utf8>>, H@1 | Parts@4]; - - {{some, S@2}, {some, _}, none} -> - [S@2, <<":"/utf8>> | Parts@4]; - - {{some, S@2}, none, none} -> - [S@2, <<":"/utf8>> | Parts@4]; - - {none, none, {some, H@2}} -> - [<<"//"/utf8>>, H@2 | Parts@4]; - - {_, _, _} -> - Parts@4 - end, - gleam@string:concat(Parts@5). - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 362). --spec origin(uri()) -> {ok, binary()} | {error, nil}. -origin(Uri) -> - {uri, Scheme, _, Host, Port, _, _, _} = Uri, - case {Host, Scheme} of - {{some, H}, {some, <<"https"/utf8>>}} when Port =:= {some, 443} -> - {ok, gleam@string:concat([<<"https://"/utf8>>, H])}; - - {{some, H@1}, {some, <<"http"/utf8>>}} when Port =:= {some, 80} -> - {ok, gleam@string:concat([<<"http://"/utf8>>, H@1])}; - - {{some, H@2}, {some, S}} when (S =:= <<"http"/utf8>>) orelse (S =:= <<"https"/utf8>>) -> - case Port of - {some, P} -> - {ok, - gleam@string:concat( - [S, - <<"://"/utf8>>, - H@2, - <<":"/utf8>>, - gleam@int:to_string(P)] - )}; - - none -> - {ok, gleam@string:concat([S, <<"://"/utf8>>, H@2])} - end; - - {_, _} -> - {error, nil} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 379). --spec drop_last(list(FKT)) -> list(FKT). -drop_last(Elements) -> - gleam@list:take(Elements, erlang:length(Elements) - 1). - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 383). --spec join_segments(list(binary())) -> binary(). -join_segments(Segments) -> - gleam@string:join([<<""/utf8>> | Segments], <<"/"/utf8>>). - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 393). --spec merge(uri(), uri()) -> {ok, uri()} | {error, nil}. -merge(Base, Relative) -> - case Base of - {uri, {some, _}, _, {some, _}, _, _, _, _} -> - case Relative of - {uri, _, _, {some, _}, _, _, _, _} -> - Path = begin - _pipe = gleam@string:split( - erlang:element(6, Relative), - <<"/"/utf8>> - ), - _pipe@1 = remove_dot_segments(_pipe), - join_segments(_pipe@1) - end, - Resolved = {uri, - gleam@option:'or'( - erlang:element(2, Relative), - erlang:element(2, Base) - ), - none, - erlang:element(4, Relative), - gleam@option:'or'( - erlang:element(5, Relative), - erlang:element(5, Base) - ), - Path, - erlang:element(7, Relative), - erlang:element(8, Relative)}, - {ok, Resolved}; - - _ -> - {New_path, New_query} = case erlang:element(6, Relative) of - <<""/utf8>> -> - {erlang:element(6, Base), - gleam@option:'or'( - erlang:element(7, Relative), - erlang:element(7, Base) - )}; - - _ -> - Path_segments = case gleam@string:starts_with( - erlang:element(6, Relative), - <<"/"/utf8>> - ) of - true -> - gleam@string:split( - erlang:element(6, Relative), - <<"/"/utf8>> - ); - - false -> - _pipe@2 = gleam@string:split( - erlang:element(6, Base), - <<"/"/utf8>> - ), - _pipe@3 = drop_last(_pipe@2), - lists:append( - _pipe@3, - gleam@string:split( - erlang:element(6, Relative), - <<"/"/utf8>> - ) - ) - end, - Path@1 = begin - _pipe@4 = Path_segments, - _pipe@5 = remove_dot_segments(_pipe@4), - join_segments(_pipe@5) - end, - {Path@1, erlang:element(7, Relative)} - end, - Resolved@1 = {uri, - erlang:element(2, Base), - none, - erlang:element(4, Base), - erlang:element(5, Base), - New_path, - New_query, - erlang:element(8, Relative)}, - {ok, Resolved@1} - end; - - _ -> - {error, nil} - end. diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam_stdlib.erl b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam_stdlib.erl deleted file mode 100644 index 562ef2372a2..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam_stdlib.erl +++ /dev/null @@ -1,565 +0,0 @@ --module(gleam_stdlib). - --export([ - map_get/2, iodata_append/2, identity/1, decode_int/1, decode_bool/1, - decode_float/1, decode_list/1, decode_option/2, decode_field/2, parse_int/1, - parse_float/1, less_than/2, string_pop_grapheme/1, string_starts_with/2, - wrap_list/1, string_ends_with/2, string_pad/4, decode_map/1, uri_parse/1, - bit_array_int_to_u32/1, bit_array_int_from_u32/1, decode_result/1, - bit_array_slice/3, decode_bit_array/1, compile_regex/2, regex_scan/2, - percent_encode/1, percent_decode/1, regex_check/2, regex_split/2, - base_decode64/1, parse_query/1, bit_array_concat/1, - bit_array_base64_encode/2, size_of_tuple/1, - decode_tuple/1, decode_tuple2/1, decode_tuple3/1, decode_tuple4/1, - decode_tuple5/1, decode_tuple6/1, tuple_get/2, classify_dynamic/1, print/1, - println/1, print_error/1, println_error/1, inspect/1, float_to_string/1, - int_from_base_string/2, utf_codepoint_list_to_string/1, contains_string/2, - crop_string/2, base16_decode/1, string_replace/3, regex_replace/3, slice/3, bit_array_to_int_and_size/1 -]). - -%% Taken from OTP's uri_string module --define(DEC2HEX(X), - if ((X) >= 0) andalso ((X) =< 9) -> (X) + $0; - ((X) >= 10) andalso ((X) =< 15) -> (X) + $A - 10 - end). - -%% Taken from OTP's uri_string module --define(HEX2DEC(X), - if ((X) >= $0) andalso ((X) =< $9) -> (X) - $0; - ((X) >= $A) andalso ((X) =< $F) -> (X) - $A + 10; - ((X) >= $a) andalso ((X) =< $f) -> (X) - $a + 10 - end). - --define(is_lowercase_char(X), (X > 96 andalso X < 123)). --define(is_underscore_char(X), (X == 95)). --define(is_digit_char(X), (X > 47 andalso X < 58)). - -uppercase(X) -> X - 32. - -map_get(Map, Key) -> - case maps:find(Key, Map) of - error -> {error, nil}; - OkFound -> OkFound - end. - -iodata_append(Iodata, String) -> [Iodata, String]. - -identity(X) -> X. - -decode_error_msg(Expected, Data) when is_binary(Expected) -> - decode_error(Expected, classify_dynamic(Data)). -decode_error(Expected, Got) when is_binary(Expected) andalso is_binary(Got) -> - {error, [{decode_error, Expected, Got, []}]}. - -classify_dynamic(nil) -> <<"Nil">>; -classify_dynamic(X) when is_boolean(X) -> <<"Bool">>; -classify_dynamic(X) when is_atom(X) -> <<"Atom">>; -classify_dynamic(X) when is_binary(X) -> <<"String">>; -classify_dynamic(X) when is_bitstring(X) -> <<"BitArray">>; -classify_dynamic(X) when is_integer(X) -> <<"Int">>; -classify_dynamic(X) when is_float(X) -> <<"Float">>; -classify_dynamic(X) when is_list(X) -> <<"List">>; -classify_dynamic(X) when is_map(X) -> <<"Dict">>; -classify_dynamic(X) when is_tuple(X) -> - iolist_to_binary(["Tuple of ", integer_to_list(tuple_size(X)), " elements"]); -classify_dynamic(X) when - is_function(X, 0) orelse is_function(X, 1) orelse is_function(X, 2) orelse - is_function(X, 3) orelse is_function(X, 4) orelse is_function(X, 5) orelse - is_function(X, 6) orelse is_function(X, 7) orelse is_function(X, 8) orelse - is_function(X, 9) orelse is_function(X, 10) orelse is_function(X, 11) orelse - is_function(X, 12) -> <<"Function">>; -classify_dynamic(_) -> <<"Some other type">>. - -decode_map(Data) when is_map(Data) -> {ok, Data}; -decode_map(Data) -> decode_error_msg(<<"Dict">>, Data). - -decode_bit_array(Data) when is_bitstring(Data) -> {ok, Data}; -decode_bit_array(Data) -> decode_error_msg(<<"BitArray">>, Data). - -decode_int(Data) when is_integer(Data) -> {ok, Data}; -decode_int(Data) -> decode_error_msg(<<"Int">>, Data). - -decode_float(Data) when is_float(Data) -> {ok, Data}; -decode_float(Data) -> decode_error_msg(<<"Float">>, Data). - -decode_bool(Data) when is_boolean(Data) -> {ok, Data}; -decode_bool(Data) -> decode_error_msg(<<"Bool">>, Data). - -decode_list(Data) when is_list(Data) -> {ok, Data}; -decode_list(Data) -> decode_error_msg(<<"List">>, Data). - -decode_field(Data, Key) when is_map(Data) -> - case Data of - #{Key := Value} -> {ok, {some, Value}}; - _ -> - {ok, none} - end; -decode_field(Data, _) -> - decode_error_msg(<<"Dict">>, Data). - -size_of_tuple(Data) -> tuple_size(Data). - -tuple_get(_tup, Index) when Index < 0 -> {error, nil}; -tuple_get(Data, Index) when Index >= tuple_size(Data) -> {error, nil}; -tuple_get(Data, Index) -> {ok, element(Index + 1, Data)}. - -decode_tuple(Data) when is_tuple(Data) -> {ok, Data}; -decode_tuple(Data) -> decode_error_msg(<<"Tuple">>, Data). - -decode_tuple2({_,_} = A) -> {ok, A}; -decode_tuple2([A,B]) -> {ok, {A,B}}; -decode_tuple2(Data) -> decode_error_msg(<<"Tuple of 2 elements">>, Data). - -decode_tuple3({_,_,_} = A) -> {ok, A}; -decode_tuple3([A,B,C]) -> {ok, {A,B,C}}; -decode_tuple3(Data) -> decode_error_msg(<<"Tuple of 3 elements">>, Data). - -decode_tuple4({_,_,_,_} = A) -> {ok, A}; -decode_tuple4([A,B,C,D]) -> {ok, {A,B,C,D}}; -decode_tuple4(Data) -> decode_error_msg(<<"Tuple of 4 elements">>, Data). - -decode_tuple5({_,_,_,_,_} = A) -> {ok, A}; -decode_tuple5([A,B,C,D,E]) -> {ok, {A,B,C,D,E}}; -decode_tuple5(Data) -> decode_error_msg(<<"Tuple of 5 elements">>, Data). - -decode_tuple6({_,_,_,_,_,_} = A) -> {ok, A}; -decode_tuple6([A,B,C,D,E,F]) -> {ok, {A,B,C,D,E,F}}; -decode_tuple6(Data) -> decode_error_msg(<<"Tuple of 6 elements">>, Data). - -decode_option(Term, F) -> - Decode = fun(Inner) -> - case F(Inner) of - {ok, Decoded} -> {ok, {some, Decoded}}; - Error -> Error - end - end, - case Term of - undefined -> {ok, none}; - error -> {ok, none}; - null -> {ok, none}; - none -> {ok, none}; - nil -> {ok, none}; - {some, Inner} -> Decode(Inner); - _ -> Decode(Term) - end. - -decode_result(Term) -> - case Term of - {ok, Inner} -> {ok, {ok, Inner}}; - ok -> {ok, {ok, nil}}; - {error, Inner} -> {ok, {error, Inner}}; - error -> {ok, {error, nil}}; - _ -> decode_error_msg(<<"Result">>, Term) - end. - -int_from_base_string(String, Base) -> - case catch binary_to_integer(String, Base) of - Int when is_integer(Int) -> {ok, Int}; - _ -> {error, nil} - end. - -parse_int(String) -> - case catch binary_to_integer(String) of - Int when is_integer(Int) -> {ok, Int}; - _ -> {error, nil} - end. - -parse_float(String) -> - case catch binary_to_float(String) of - Float when is_float(Float) -> {ok, Float}; - _ -> {error, nil} - end. - -less_than(Lhs, Rhs) -> - Lhs < Rhs. - -string_starts_with(_, <<>>) -> true; -string_starts_with(String, Prefix) when byte_size(Prefix) > byte_size(String) -> false; -string_starts_with(String, Prefix) -> - PrefixSize = byte_size(Prefix), - Prefix == binary_part(String, 0, PrefixSize). - -string_ends_with(_, <<>>) -> true; -string_ends_with(String, Suffix) when byte_size(Suffix) > byte_size(String) -> false; -string_ends_with(String, Suffix) -> - SuffixSize = byte_size(Suffix), - Suffix == binary_part(String, byte_size(String) - SuffixSize, SuffixSize). - -string_pad(String, Length, Dir, PadString) -> - Chars = string:pad(String, Length, Dir, binary_to_list(PadString)), - case unicode:characters_to_binary(Chars) of - Bin when is_binary(Bin) -> Bin; - Error -> erlang:error({gleam_error, {string_invalid_utf8, Error}}) - end. - -string_pop_grapheme(String) -> - case string:next_grapheme(String) of - [ Next | Rest ] when is_binary(Rest) -> - {ok, {unicode:characters_to_binary([Next]), Rest}}; - - [ Next | Rest ] -> - {ok, {unicode:characters_to_binary([Next]), unicode:characters_to_binary(Rest)}}; - - _ -> {error, nil} - end. - -bit_array_concat(BitArrays) -> - list_to_bitstring(BitArrays). - --if(?OTP_RELEASE >= 26). -bit_array_base64_encode(Bin, Padding) -> - base64:encode(Bin, #{padding => Padding}). --else. -bit_array_base64_encode(_Bin, _Padding) -> - erlang:error(<<"Erlang OTP/26 or higher is required to use base64:encode">>). --endif. - -bit_array_slice(Bin, Pos, Len) -> - try {ok, binary:part(Bin, Pos, Len)} - catch error:badarg -> {error, nil} - end. - -bit_array_int_to_u32(I) when 0 =< I, I < 4294967296 -> - {ok, <>}; -bit_array_int_to_u32(_) -> - {error, nil}. - -bit_array_int_from_u32(<>) -> - {ok, I}; -bit_array_int_from_u32(_) -> - {error, nil}. - -compile_regex(String, Options) -> - {options, Caseless, Multiline} = Options, - OptionsList = [ - unicode, - ucp, - Caseless andalso caseless, - Multiline andalso multiline - ], - FilteredOptions = [Option || Option <- OptionsList, Option /= false], - case re:compile(String, FilteredOptions) of - {ok, MP} -> {ok, MP}; - {error, {Str, Pos}} -> - {error, {compile_error, unicode:characters_to_binary(Str), Pos}} - end. - -regex_check(Regex, String) -> - re:run(String, Regex) /= nomatch. - -regex_split(Regex, String) -> - re:split(String, Regex). - -regex_submatches(_, {-1, 0}) -> none; -regex_submatches(String, {Start, Length}) -> - BinarySlice = binary:part(String, {Start, Length}), - case string:is_empty(binary_to_list(BinarySlice)) of - true -> none; - false -> {some, BinarySlice} - end. - -regex_matches(String, [{Start, Length} | Submatches]) -> - Submatches1 = lists:map(fun(X) -> regex_submatches(String, X) end, Submatches), - {match, binary:part(String, Start, Length), Submatches1}. - -regex_scan(Regex, String) -> - case re:run(String, Regex, [global]) of - {match, Captured} -> lists:map(fun(X) -> regex_matches(String, X) end, Captured); - nomatch -> [] - end. - -regex_replace(Regex, Subject, Replacement) -> - re:replace(Subject, Regex, Replacement, [global, {return, binary}]). - -base_decode64(S) -> - try {ok, base64:decode(S)} - catch error:_ -> {error, nil} - end. - -wrap_list(X) when is_list(X) -> X; -wrap_list(X) -> [X]. - -parse_query(Query) -> - case uri_string:dissect_query(Query) of - {error, _, _} -> {error, nil}; - Pairs -> - Pairs1 = lists:map(fun - ({K, true}) -> {K, <<"">>}; - (Pair) -> Pair - end, Pairs), - {ok, Pairs1} - end. - -percent_encode(B) -> percent_encode(B, <<>>). -percent_encode(<<>>, Acc) -> - Acc; -percent_encode(<>, Acc) -> - case percent_ok(H) of - true -> - percent_encode(T, <>); - false -> - <> = <>, - percent_encode(T, <>) - end. - -percent_decode(Cs) -> percent_decode(Cs, <<>>). -percent_decode(<<$%, C0, C1, Cs/binary>>, Acc) -> - case is_hex_digit(C0) andalso is_hex_digit(C1) of - true -> - B = ?HEX2DEC(C0)*16+?HEX2DEC(C1), - percent_decode(Cs, <>); - false -> - {error, nil} - end; -percent_decode(<>, Acc) -> - percent_decode(Cs, <>); -percent_decode(<<>>, Acc) -> - check_utf8(Acc). - -percent_ok($!) -> true; -percent_ok($$) -> true; -percent_ok($') -> true; -percent_ok($() -> true; -percent_ok($)) -> true; -percent_ok($*) -> true; -percent_ok($+) -> true; -percent_ok($-) -> true; -percent_ok($.) -> true; -percent_ok($_) -> true; -percent_ok($~) -> true; -percent_ok(C) when $0 =< C, C =< $9 -> true; -percent_ok(C) when $A =< C, C =< $Z -> true; -percent_ok(C) when $a =< C, C =< $z -> true; -percent_ok(_) -> false. - -is_hex_digit(C) -> - ($0 =< C andalso C =< $9) orelse ($a =< C andalso C =< $f) orelse ($A =< C andalso C =< $F). - -check_utf8(Cs) -> - case unicode:characters_to_list(Cs) of - {incomplete, _, _} -> {error, nil}; - {error, _, _} -> {error, nil}; - _ -> {ok, Cs} - end. - -uri_parse(String) -> - case uri_string:parse(String) of - {error, _, _} -> {error, nil}; - Uri -> - {ok, {uri, - maps_get_optional(Uri, scheme), - maps_get_optional(Uri, userinfo), - maps_get_optional(Uri, host), - maps_get_optional(Uri, port), - maps_get_or(Uri, path, <<>>), - maps_get_optional(Uri, query), - maps_get_optional(Uri, fragment) - }} - end. - -maps_get_optional(Map, Key) -> - try {some, maps:get(Key, Map)} - catch _:_ -> none - end. - -maps_get_or(Map, Key, Default) -> - try maps:get(Key, Map) - catch _:_ -> Default - end. - -print(String) -> - io:put_chars(String), - nil. - -println(String) -> - io:put_chars([String, $\n]), - nil. - -print_error(String) -> - io:put_chars(standard_error, String), - nil. - -println_error(String) -> - io:put_chars(standard_error, [String, $\n]), - nil. - -inspect(true) -> - "True"; -inspect(false) -> - "False"; -inspect(nil) -> - "Nil"; -inspect(Data) when is_map(Data) -> - Fields = [ - [<<"#(">>, inspect(Key), <<", ">>, inspect(Value), <<")">>] - || {Key, Value} <- maps:to_list(Data) - ], - ["dict.from_list([", lists:join(", ", Fields), "])"]; -inspect(Atom) when is_atom(Atom) -> - Binary = erlang:atom_to_binary(Atom), - case inspect_maybe_gleam_atom(Binary, none, <<>>) of - {ok, Inspected} -> Inspected; - {error, _} -> ["atom.create_from_string(\"", Binary, "\")"] - end; -inspect(Any) when is_integer(Any) -> - erlang:integer_to_list(Any); -inspect(Any) when is_float(Any) -> - io_lib_format:fwrite_g(Any); -inspect(Binary) when is_binary(Binary) -> - case inspect_maybe_utf8_string(Binary, <<>>) of - {ok, InspectedUtf8String} -> InspectedUtf8String; - {error, not_a_utf8_string} -> - Segments = [erlang:integer_to_list(X) || <> <= Binary], - ["<<", lists:join(", ", Segments), ">>"] - end; -inspect(Bits) when is_bitstring(Bits) -> - inspect_bit_array(Bits); -inspect(List) when is_list(List) -> - case inspect_list(List) of - {proper, Elements} -> ["[", Elements, "]"]; - {improper, Elements} -> ["//erl([", Elements, "])"] - end; -inspect(Any) when is_tuple(Any) % Record constructors - andalso is_atom(element(1, Any)) - andalso element(1, Any) =/= false - andalso element(1, Any) =/= true - andalso element(1, Any) =/= nil --> - [Atom | ArgsList] = erlang:tuple_to_list(Any), - Args = lists:join(<<", ">>, - lists:map(fun inspect/1, ArgsList) - ), - [inspect(Atom), "(", Args, ")"]; -inspect(Tuple) when is_tuple(Tuple) -> - Elements = lists:map(fun inspect/1, erlang:tuple_to_list(Tuple)), - ["#(", lists:join(", ", Elements), ")"]; -inspect(Any) when is_function(Any) -> - {arity, Arity} = erlang:fun_info(Any, arity), - ArgsAsciiCodes = lists:seq($a, $a + Arity - 1), - Args = lists:join(<<", ">>, - lists:map(fun(Arg) -> <> end, ArgsAsciiCodes) - ), - ["//fn(", Args, ") { ... }"]; -inspect(Any) -> - ["//erl(", io_lib:format("~p", [Any]), ")"]. - - -inspect_maybe_gleam_atom(<<>>, none, _) -> - {error, nil}; -inspect_maybe_gleam_atom(<>, none, _) when ?is_digit_char(First) -> - {error, nil}; -inspect_maybe_gleam_atom(<<"_", _Rest/binary>>, none, _) -> - {error, nil}; -inspect_maybe_gleam_atom(<<"_">>, _PrevChar, _Acc) -> - {error, nil}; -inspect_maybe_gleam_atom(<<"_", _Rest/binary>>, $_, _Acc) -> - {error, nil}; -inspect_maybe_gleam_atom(<>, _PrevChar, _Acc) - when not (?is_lowercase_char(First) orelse ?is_underscore_char(First) orelse ?is_digit_char(First)) -> - {error, nil}; -inspect_maybe_gleam_atom(<>, none, Acc) -> - inspect_maybe_gleam_atom(Rest, First, <>); -inspect_maybe_gleam_atom(<<"_", Rest/binary>>, _PrevChar, Acc) -> - inspect_maybe_gleam_atom(Rest, $_, Acc); -inspect_maybe_gleam_atom(<>, $_, Acc) -> - inspect_maybe_gleam_atom(Rest, First, <>); -inspect_maybe_gleam_atom(<>, _PrevChar, Acc) -> - inspect_maybe_gleam_atom(Rest, First, <>); -inspect_maybe_gleam_atom(<<>>, _PrevChar, Acc) -> - {ok, Acc}; -inspect_maybe_gleam_atom(A, B, C) -> - erlang:display({A, B, C}), - throw({gleam_error, A, B, C}). - -inspect_list([]) -> - {proper, []}; -inspect_list([First]) -> - {proper, [inspect(First)]}; -inspect_list([First | Rest]) when is_list(Rest) -> - {Kind, Inspected} = inspect_list(Rest), - {Kind, [inspect(First), <<", ">> | Inspected]}; -inspect_list([First | ImproperTail]) -> - {improper, [inspect(First), <<" | ">>, inspect(ImproperTail)]}. - -inspect_bit_array(Bits) -> - Text = inspect_bit_array(Bits, <<"<<">>), - <>">>. - -inspect_bit_array(<<>>, Acc) -> - Acc; -inspect_bit_array(<>, Acc) -> - inspect_bit_array(Rest, append_segment(Acc, erlang:integer_to_binary(X))); -inspect_bit_array(Rest, Acc) -> - Size = bit_size(Rest), - <> = Rest, - X1 = erlang:integer_to_binary(X), - Size1 = erlang:integer_to_binary(Size), - Segment = <>, - inspect_bit_array(<<>>, append_segment(Acc, Segment)). - -bit_array_to_int_and_size(A) -> - Size = bit_size(A), - <> = A, - {A1, Size}. - -append_segment(<<"<<">>, Segment) -> - <<"<<", Segment/binary>>; -append_segment(Acc, Segment) -> - <>. - - -inspect_maybe_utf8_string(Binary, Acc) -> - case Binary of - <<>> -> {ok, <<$", Acc/binary, $">>}; - <> -> - Escaped = case First of - $" -> <<$\\, $">>; - $\\ -> <<$\\, $\\>>; - $\r -> <<$\\, $r>>; - $\n -> <<$\\, $n>>; - $\t -> <<$\\, $t>>; - $\f -> <<$\\, $f>>; - X when X > 126, X < 160 -> convert_to_u(X); - X when X < 32 -> convert_to_u(X); - Other -> <> - end, - inspect_maybe_utf8_string(Rest, <>); - _ -> {error, not_a_utf8_string} - end. - -convert_to_u(Code) -> - list_to_binary(io_lib:format("\\u{~4.16.0B}", [Code])). - -float_to_string(Float) when is_float(Float) -> - erlang:iolist_to_binary(io_lib_format:fwrite_g(Float)). - -utf_codepoint_list_to_string(List) -> - case unicode:characters_to_binary(List) of - {error, _} -> erlang:error({gleam_error, {string_invalid_utf8, List}}); - Binary -> Binary - end. - -crop_string(String, Prefix) -> - case string:find(String, Prefix) of - nomatch -> String; - New -> New - end. - -contains_string(String, Substring) -> - is_bitstring(string:find(String, Substring)). - -base16_decode(String) -> - try - {ok, binary:decode_hex(String)} - catch - _:_ -> {error, nil} - end. - -string_replace(String, Pattern, Replacement) -> - string:replace(String, Pattern, Replacement, all). - -slice(String, Index, Length) -> - case string:slice(String, Index, Length) of - X when is_binary(X) -> X; - X when is_list(X) -> unicode:characters_to_binary(X) - end. diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam_stdlib.mjs b/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam_stdlib.mjs deleted file mode 100644 index 74df3d05952..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_stdlib/gleam_stdlib.mjs +++ /dev/null @@ -1,992 +0,0 @@ -import { - BitArray, - Error, - List, - Ok, - Result, - UtfCodepoint, - stringBits, - toBitArray, - NonEmpty, - CustomType, -} from "./gleam.mjs"; -import { - CompileError as RegexCompileError, - Match as RegexMatch, -} from "./gleam/regex.mjs"; -import { DecodeError } from "./gleam/dynamic.mjs"; -import { Some, None } from "./gleam/option.mjs"; -import { Eq, Gt, Lt } from "./gleam/order.mjs"; -import Dict from "./dict.mjs"; - -const Nil = undefined; -const NOT_FOUND = {}; - -export function identity(x) { - return x; -} - -export function parse_int(value) { - if (/^[-+]?(\d+)$/.test(value)) { - return new Ok(parseInt(value)); - } else { - return new Error(Nil); - } -} - -export function parse_float(value) { - if (/^[-+]?(\d+)\.(\d+)([eE][-+]?\d+)?$/.test(value)) { - return new Ok(parseFloat(value)); - } else { - return new Error(Nil); - } -} - -export function to_string(term) { - return term.toString(); -} - -export function float_to_string(float) { - const string = float.toString().replace('+', ''); - if (string.indexOf(".") >= 0) { - return string; - } else { - const index = string.indexOf("e"); - if (index >= 0) { - return string.slice(0, index) + '.0' + string.slice(index); - } else { - return string + ".0"; - } - } -} - -export function int_to_base_string(int, base) { - return int.toString(base).toUpperCase(); -} - -const int_base_patterns = { - 2: /[^0-1]/, - 3: /[^0-2]/, - 4: /[^0-3]/, - 5: /[^0-4]/, - 6: /[^0-5]/, - 7: /[^0-6]/, - 8: /[^0-7]/, - 9: /[^0-8]/, - 10: /[^0-9]/, - 11: /[^0-9a]/, - 12: /[^0-9a-b]/, - 13: /[^0-9a-c]/, - 14: /[^0-9a-d]/, - 15: /[^0-9a-e]/, - 16: /[^0-9a-f]/, - 17: /[^0-9a-g]/, - 18: /[^0-9a-h]/, - 19: /[^0-9a-i]/, - 20: /[^0-9a-j]/, - 21: /[^0-9a-k]/, - 22: /[^0-9a-l]/, - 23: /[^0-9a-m]/, - 24: /[^0-9a-n]/, - 25: /[^0-9a-o]/, - 26: /[^0-9a-p]/, - 27: /[^0-9a-q]/, - 28: /[^0-9a-r]/, - 29: /[^0-9a-s]/, - 30: /[^0-9a-t]/, - 31: /[^0-9a-u]/, - 32: /[^0-9a-v]/, - 33: /[^0-9a-w]/, - 34: /[^0-9a-x]/, - 35: /[^0-9a-y]/, - 36: /[^0-9a-z]/, -}; - -export function int_from_base_string(string, base) { - if (int_base_patterns[base].test(string.replace(/^-/, "").toLowerCase())) { - return new Error(Nil); - } - - const result = parseInt(string, base); - - if (isNaN(result)) { - return new Error(Nil); - } - - return new Ok(result); -} - -export function string_replace(string, target, substitute) { - if (typeof string.replaceAll !== "undefined") { - return string.replaceAll(target, substitute); - } - // Fallback for older Node.js versions: - // 1. - // 2. - // TODO: This fallback could be remove once Node.js 14 is EOL - // aka on or after 2024-04-30 - return string.replace( - // $& means the whole matched string - new RegExp(target.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g"), - substitute, - ); -} - -export function string_reverse(string) { - return [...string].reverse().join(""); -} - -export function string_length(string) { - if (string === "") { - return 0; - } - const iterator = graphemes_iterator(string); - if (iterator) { - let i = 0; - for (const _ of iterator) { - i++; - } - return i; - } else { - return string.match(/./gsu).length; - } -} - -export function graphemes(string) { - const iterator = graphemes_iterator(string); - if (iterator) { - return List.fromArray(Array.from(iterator).map((item) => item.segment)); - } else { - return List.fromArray(string.match(/./gsu)); - } -} - -let segmenter = undefined; - -function graphemes_iterator(string) { - if (globalThis.Intl && Intl.Segmenter) { - segmenter ||= new Intl.Segmenter(); - return segmenter.segment(string)[Symbol.iterator](); - } -} - -export function pop_grapheme(string) { - let first; - const iterator = graphemes_iterator(string); - if (iterator) { - first = iterator.next().value?.segment; - } else { - first = string.match(/./su)?.[0]; - } - if (first) { - return new Ok([first, string.slice(first.length)]); - } else { - return new Error(Nil); - } -} - -export function lowercase(string) { - return string.toLowerCase(); -} - -export function uppercase(string) { - return string.toUpperCase(); -} - -export function less_than(a, b) { - return a < b; -} - -export function add(a, b) { - return a + b; -} - -export function split(xs, pattern) { - return List.fromArray(xs.split(pattern)); -} - -export function join(xs, separator) { - const iterator = xs[Symbol.iterator](); - let result = iterator.next().value || ""; - let current = iterator.next(); - while (!current.done) { - result = result + separator + current.value; - current = iterator.next(); - } - return result; -} - -export function concat(xs) { - let result = ""; - for (const x of xs) { - result = result + x; - } - return result; -} - -export function length(data) { - return data.length; -} - -export function string_slice(string, idx, len) { - if (len <= 0 || idx >= string.length) { - return ""; - } - - const iterator = graphemes_iterator(string); - if (iterator) { - while (idx-- > 0) { - iterator.next(); - } - - let result = ""; - - while (len-- > 0) { - const v = iterator.next().value; - if (v === undefined) { - break; - } - - result += v.segment; - } - - return result; - } else { - return string.match(/./gsu).slice(idx, idx + len).join(""); - } -} - -export function crop_string(string, substring) { - return string.substring(string.indexOf(substring)); -} - -export function contains_string(haystack, needle) { - return haystack.indexOf(needle) >= 0; -} - -export function starts_with(haystack, needle) { - return haystack.startsWith(needle); -} - -export function ends_with(haystack, needle) { - return haystack.endsWith(needle); -} - -export function split_once(haystack, needle) { - const index = haystack.indexOf(needle); - if (index >= 0) { - const before = haystack.slice(0, index); - const after = haystack.slice(index + needle.length); - return new Ok([before, after]); - } else { - return new Error(Nil); - } -} - -const unicode_whitespaces = [ - "\u0020", // Space - "\u0009", // Horizontal tab - "\u000A", // Line feed - "\u000B", // Vertical tab - "\u000C", // Form feed - "\u000D", // Carriage return - "\u0085", // Next line - "\u2028", // Line separator - "\u2029", // Paragraph separator -].join(""); - -const left_trim_regex = new RegExp(`^([${unicode_whitespaces}]*)`, "g"); -const right_trim_regex = new RegExp(`([${unicode_whitespaces}]*)$`, "g"); - -export function trim(string) { - return trim_left(trim_right(string)); -} - -export function trim_left(string) { - return string.replace(left_trim_regex, ""); -} - -export function trim_right(string) { - return string.replace(right_trim_regex, ""); -} - -export function bit_array_from_string(string) { - return toBitArray([stringBits(string)]); -} - -export function bit_array_concat(bit_arrays) { - return toBitArray(bit_arrays.toArray().map((b) => b.buffer)); -} - -export function console_log(term) { - console.log(term); -} - -export function console_error(term) { - console.error(term); -} - -export function crash(message) { - throw new globalThis.Error(message); -} - -export function bit_array_to_string(bit_array) { - try { - const decoder = new TextDecoder("utf-8", { fatal: true }); - return new Ok(decoder.decode(bit_array.buffer)); - } catch { - return new Error(Nil); - } -} - -export function print(string) { - if (typeof process === "object") { - process.stdout.write(string); // We can write without a trailing newline - } else if (typeof Deno === "object") { - Deno.stdout.writeSync(new TextEncoder().encode(string)); // We can write without a trailing newline - } else { - console.log(string); // We're in a browser. Newlines are mandated - } -} - -export function print_error(string) { - if (typeof process === "object" && process.stderr?.write) { - process.stderr.write(string); // We can write without a trailing newline - } else if (typeof Deno === "object") { - Deno.stderr.writeSync(new TextEncoder().encode(string)); // We can write without a trailing newline - } else { - console.error(string); // We're in a browser. Newlines are mandated - } -} - -export function print_debug(string) { - if (typeof process === "object" && process.stderr?.write) { - process.stderr.write(string + "\n"); // If we're in Node.js, use `stderr` - } else if (typeof Deno === "object") { - Deno.stderr.writeSync(new TextEncoder().encode(string + "\n")); // If we're in Deno, use `stderr` - } else { - console.log(string); // Otherwise, use `console.log` (so that it doesn't look like an error) - } -} - -export function ceiling(float) { - return Math.ceil(float); -} - -export function floor(float) { - return Math.floor(float); -} - -export function round(float) { - return Math.round(float); -} - -export function truncate(float) { - return Math.trunc(float); -} - -export function power(base, exponent) { - // It is checked in Gleam that: - // - The base is non-negative and that the exponent is not fractional. - // - The base is non-zero and the exponent is non-negative (otherwise - // the result will essentially be division by zero). - // It can thus be assumed that valid input is passed to the Math.pow - // function and a NaN or Infinity value will not be produced. - return Math.pow(base, exponent); -} - -export function random_uniform() { - const random_uniform_result = Math.random(); - // With round-to-nearest-even behavior, the ranges claimed for the functions below - // (excluding the one for Math.random() itself) aren't exact. - // If extremely large bounds are chosen (2^53 or higher), - // it's possible in extremely rare cases to calculate the usually-excluded upper bound. - // Note that as numbers in JavaScript are IEEE 754 floating point numbers - // See: - // Because of this, we just loop 'until' we get a valid result where 0.0 <= x < 1.0: - if (random_uniform_result === 1.0) { - return random_uniform(); - } - return random_uniform_result; -} - -export function bit_array_slice(bits, position, length) { - const start = Math.min(position, position + length); - const end = Math.max(position, position + length); - if (start < 0 || end > bits.length) return new Error(Nil); - const byteOffset = bits.buffer.byteOffset + start; - const buffer = new Uint8Array( - bits.buffer.buffer, - byteOffset, - Math.abs(length), - ); - return new Ok(new BitArray(buffer)); -} - -export function codepoint(int) { - return new UtfCodepoint(int); -} - -export function string_to_codepoint_integer_list(string) { - return List.fromArray(Array.from(string).map((item) => item.codePointAt(0))); -} - -export function utf_codepoint_list_to_string(utf_codepoint_integer_list) { - return utf_codepoint_integer_list - .toArray() - .map((x) => String.fromCodePoint(x.value)) - .join(""); -} - -export function utf_codepoint_to_int(utf_codepoint) { - return utf_codepoint.value; -} - -export function regex_check(regex, string) { - regex.lastIndex = 0; - return regex.test(string); -} - -export function compile_regex(pattern, options) { - try { - let flags = "gu"; - if (options.case_insensitive) flags += "i"; - if (options.multi_line) flags += "m"; - return new Ok(new RegExp(pattern, flags)); - } catch (error) { - const number = (error.columnNumber || 0) | 0; - return new Error(new RegexCompileError(error.message, number)); - } -} - -export function regex_split(regex, string) { - return List.fromArray( - string.split(regex).map((item) => (item === undefined ? "" : item)), - ); -} - -export function regex_scan(regex, string) { - const matches = Array.from(string.matchAll(regex)).map((match) => { - const content = match[0]; - const submatches = []; - for (let n = match.length - 1; n > 0; n--) { - if (match[n]) { - submatches[n - 1] = new Some(match[n]); - continue; - } - if (submatches.length > 0) { - submatches[n - 1] = new None(); - } - } - return new RegexMatch(content, List.fromArray(submatches)); - }); - return List.fromArray(matches); -} - -export function regex_replace(regex, original_string, replacement) { - return original_string.replaceAll(regex, replacement); -} - -export function new_map() { - return Dict.new(); -} - -export function map_size(map) { - return map.size; -} - -export function map_to_list(map) { - return List.fromArray(map.entries()); -} - -export function map_remove(key, map) { - return map.delete(key); -} - -export function map_get(map, key) { - const value = map.get(key, NOT_FOUND); - if (value === NOT_FOUND) { - return new Error(Nil); - } - return new Ok(value); -} - -export function map_insert(key, value, map) { - return map.set(key, value); -} - -function unsafe_percent_decode(string) { - return decodeURIComponent(string || ""); -} - -function unsafe_percent_decode_query(string) { - return decodeURIComponent((string || "").replace("+", " ")); -} - -export function percent_decode(string) { - try { - return new Ok(unsafe_percent_decode(string)); - } catch { - return new Error(Nil); - } -} - -export function percent_encode(string) { - return encodeURIComponent(string).replace("%2B", "+"); -} - -export function parse_query(query) { - try { - const pairs = []; - for (const section of query.split("&")) { - const [key, value] = section.split("="); - if (!key) continue; - - const decodedKey = unsafe_percent_decode_query(key); - const decodedValue = unsafe_percent_decode_query(value); - pairs.push([decodedKey, decodedValue]); - } - return new Ok(List.fromArray(pairs)); - } catch { - return new Error(Nil); - } -} - -const b64EncodeLookup = [ - 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, - 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, - 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, - 122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43, 47, -]; - -let b64TextDecoder; - -// Implementation based on https://github.com/mitschabaude/fast-base64/blob/main/js.js -export function encode64(bit_array, padding) { - b64TextDecoder ??= new TextDecoder(); - - const bytes = bit_array.buffer; - - const m = bytes.length; - const k = m % 3; - const n = Math.floor(m / 3) * 4 + (k && k + 1); - const N = Math.ceil(m / 3) * 4; - const encoded = new Uint8Array(N); - - for (let i = 0, j = 0; j < m; i += 4, j += 3) { - const y = (bytes[j] << 16) + (bytes[j + 1] << 8) + (bytes[j + 2] | 0); - encoded[i] = b64EncodeLookup[y >> 18]; - encoded[i + 1] = b64EncodeLookup[(y >> 12) & 0x3f]; - encoded[i + 2] = b64EncodeLookup[(y >> 6) & 0x3f]; - encoded[i + 3] = b64EncodeLookup[y & 0x3f]; - } - - let base64 = b64TextDecoder.decode(new Uint8Array(encoded.buffer, 0, n)); - - if (padding) { - if (k === 1) { - base64 += "=="; - } else if (k === 2) { - base64 += "="; - } - } - - return base64; -} - -// From https://developer.mozilla.org/en-US/docs/Glossary/Base64 -export function decode64(sBase64) { - try { - const binString = atob(sBase64); - const length = binString.length; - const array = new Uint8Array(length); - for (let i = 0; i < length; i++) { - array[i] = binString.charCodeAt(i); - } - return new Ok(new BitArray(array)); - } catch { - return new Error(Nil); - } -} - -export function classify_dynamic(data) { - if (typeof data === "string") { - return "String"; - } else if (typeof data === "boolean") { - return "Bool"; - } else if (data instanceof Result) { - return "Result"; - } else if (data instanceof List) { - return "List"; - } else if (data instanceof BitArray) { - return "BitArray"; - } else if (data instanceof Dict) { - return "Dict"; - } else if (Number.isInteger(data)) { - return "Int"; - } else if (Array.isArray(data)) { - return `Tuple of ${data.length} elements`; - } else if (typeof data === "number") { - return "Float"; - } else if (data === null) { - return "Null"; - } else if (data === undefined) { - return "Nil"; - } else { - const type = typeof data; - return type.charAt(0).toUpperCase() + type.slice(1); - } -} - -function decoder_error(expected, got) { - return decoder_error_no_classify(expected, classify_dynamic(got)); -} - -function decoder_error_no_classify(expected, got) { - return new Error( - List.fromArray([new DecodeError(expected, got, List.fromArray([]))]), - ); -} - -export function decode_string(data) { - return typeof data === "string" - ? new Ok(data) - : decoder_error("String", data); -} - -export function decode_int(data) { - return Number.isInteger(data) ? new Ok(data) : decoder_error("Int", data); -} - -export function decode_float(data) { - return typeof data === "number" ? new Ok(data) : decoder_error("Float", data); -} - -export function decode_bool(data) { - return typeof data === "boolean" ? new Ok(data) : decoder_error("Bool", data); -} - -export function decode_bit_array(data) { - if (data instanceof BitArray) { - return new Ok(data); - } - if (data instanceof Uint8Array) { - return new Ok(new BitArray(data)); - } - return decoder_error("BitArray", data); -} - -export function decode_tuple(data) { - return Array.isArray(data) ? new Ok(data) : decoder_error("Tuple", data); -} - -export function decode_tuple2(data) { - return decode_tupleN(data, 2); -} - -export function decode_tuple3(data) { - return decode_tupleN(data, 3); -} - -export function decode_tuple4(data) { - return decode_tupleN(data, 4); -} - -export function decode_tuple5(data) { - return decode_tupleN(data, 5); -} - -export function decode_tuple6(data) { - return decode_tupleN(data, 6); -} - -function decode_tupleN(data, n) { - if (Array.isArray(data) && data.length == n) { - return new Ok(data); - } - - const list = decode_exact_length_list(data, n); - if (list) return new Ok(list); - - return decoder_error(`Tuple of ${n} elements`, data); -} - -function decode_exact_length_list(data, n) { - if (!(data instanceof List)) return; - - const elements = []; - let current = data; - - for (let i = 0; i < n; i++) { - if (!(current instanceof NonEmpty)) break; - elements.push(current.head); - current = current.tail; - } - - if (elements.length === n && !(current instanceof NonEmpty)) return elements; -} - -export function tuple_get(data, index) { - return index >= 0 && data.length > index - ? new Ok(data[index]) - : new Error(Nil); -} - -export function decode_list(data) { - if (Array.isArray(data)) { - return new Ok(List.fromArray(data)); - } - return data instanceof List ? new Ok(data) : decoder_error("List", data); -} - -export function decode_result(data) { - return data instanceof Result ? new Ok(data) : decoder_error("Result", data); -} - -export function decode_map(data) { - if (data instanceof Dict) { - return new Ok(data); - } - if (data instanceof Map || data instanceof WeakMap) { - return new Ok(Dict.fromMap(data)); - } - if (data == null) { - return decoder_error("Dict", data); - } - if (typeof data !== "object") { - return decoder_error("Dict", data); - } - const proto = Object.getPrototypeOf(data); - if (proto === Object.prototype || proto === null) { - return new Ok(Dict.fromObject(data)); - } - return decoder_error("Dict", data); -} - -export function decode_option(data, decoder) { - if (data === null || data === undefined || data instanceof None) - return new Ok(new None()); - if (data instanceof Some) data = data[0]; - const result = decoder(data); - if (result.isOk()) { - return new Ok(new Some(result[0])); - } else { - return result; - } -} - -export function decode_field(value, name) { - const not_a_map_error = () => decoder_error("Dict", value); - - if ( - value instanceof Dict || - value instanceof WeakMap || - value instanceof Map - ) { - const entry = map_get(value, name); - return new Ok(entry.isOk() ? new Some(entry[0]) : new None()); - } else if (value === null) { - return not_a_map_error(); - } else if (Object.getPrototypeOf(value) == Object.prototype) { - return try_get_field(value, name, () => new Ok(new None())); - } else { - return try_get_field(value, name, not_a_map_error); - } -} - -function try_get_field(value, field, or_else) { - try { - return field in value ? new Ok(new Some(value[field])) : or_else(); - } catch { - return or_else(); - } -} - -export function byte_size(string) { - return new TextEncoder().encode(string).length; -} - -// In Javascript bitwise operations convert numbers to a sequence of 32 bits -// while Erlang uses arbitrary precision. -// To get around this problem and get consistent results use BigInt and then -// downcast the value back to a Number value. - -export function bitwise_and(x, y) { - return Number(BigInt(x) & BigInt(y)); -} - -export function bitwise_not(x) { - return Number(~BigInt(x)); -} - -export function bitwise_or(x, y) { - return Number(BigInt(x) | BigInt(y)); -} - -export function bitwise_exclusive_or(x, y) { - return Number(BigInt(x) ^ BigInt(y)); -} - -export function bitwise_shift_left(x, y) { - return Number(BigInt(x) << BigInt(y)); -} - -export function bitwise_shift_right(x, y) { - return Number(BigInt(x) >> BigInt(y)); -} - -export function inspect(v) { - const t = typeof v; - if (v === true) return "True"; - if (v === false) return "False"; - if (v === null) return "//js(null)"; - if (v === undefined) return "Nil"; - if (t === "string") return inspectString(v); - if (t === "bigint" || Number.isInteger(v)) return v.toString(); - if (t === "number") return float_to_string(v); - if (Array.isArray(v)) return `#(${v.map(inspect).join(", ")})`; - if (v instanceof List) return inspectList(v); - if (v instanceof UtfCodepoint) return inspectUtfCodepoint(v); - if (v instanceof BitArray) return inspectBitArray(v); - if (v instanceof CustomType) return inspectCustomType(v); - if (v instanceof Dict) return inspectDict(v); - if (v instanceof Set) return `//js(Set(${[...v].map(inspect).join(", ")}))`; - if (v instanceof RegExp) return `//js(${v})`; - if (v instanceof Date) return `//js(Date("${v.toISOString()}"))`; - if (v instanceof Function) { - const args = []; - for (const i of Array(v.length).keys()) - args.push(String.fromCharCode(i + 97)); - return `//fn(${args.join(", ")}) { ... }`; - } - return inspectObject(v); -} - -function inspectString(str) { - let new_str = '"'; - for (let i = 0; i < str.length; i++) { - let char = str[i]; - switch (char) { - case "\n": - new_str += "\\n"; - break; - case "\r": - new_str += "\\r"; - break; - case "\t": - new_str += "\\t"; - break; - case "\f": - new_str += "\\f"; - break; - case "\\": - new_str += "\\\\"; - break; - case '"': - new_str += '\\"'; - break; - default: - if (char < " " || (char > "~" && char < "\u{00A0}")) { - new_str += - "\\u{" + - char.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0") + - "}"; - } else { - new_str += char; - } - } - } - new_str += '"'; - return new_str; -} - -function inspectDict(map) { - let body = "dict.from_list(["; - let first = true; - map.forEach((value, key) => { - if (!first) body = body + ", "; - body = body + "#(" + inspect(key) + ", " + inspect(value) + ")"; - first = false; - }); - return body + "])"; -} - -function inspectObject(v) { - const name = Object.getPrototypeOf(v)?.constructor?.name || "Object"; - const props = []; - for (const k of Object.keys(v)) { - props.push(`${inspect(k)}: ${inspect(v[k])}`); - } - const body = props.length ? " " + props.join(", ") + " " : ""; - const head = name === "Object" ? "" : name + " "; - return `//js(${head}{${body}})`; -} - -function inspectCustomType(record) { - const props = Object.keys(record) - .map((label) => { - const value = inspect(record[label]); - return isNaN(parseInt(label)) ? `${label}: ${value}` : value; - }) - .join(", "); - return props - ? `${record.constructor.name}(${props})` - : record.constructor.name; -} - -export function inspectList(list) { - return `[${list.toArray().map(inspect).join(", ")}]`; -} - -export function inspectBitArray(bits) { - return `<<${Array.from(bits.buffer).join(", ")}>>`; -} - -export function inspectUtfCodepoint(codepoint) { - return `//utfcodepoint(${String.fromCodePoint(codepoint.value)})`; -} - -export function base16_encode(bit_array) { - let result = ""; - for (const byte of bit_array.buffer) { - result += byte.toString(16).padStart(2, "0").toUpperCase(); - } - return result; -} - -export function base16_decode(string) { - const bytes = new Uint8Array(string.length / 2); - for (let i = 0; i < string.length; i += 2) { - const a = parseInt(string[i], 16); - const b = parseInt(string[i + 1], 16); - if (isNaN(a) || isNaN(b)) return new Error(Nil); - bytes[i / 2] = a * 16 + b; - } - return new Ok(new BitArray(bytes)); -} - -export function bit_array_inspect(bits, acc) { - return `${acc}${[...bits.buffer].join(", ")}`; -} - -export function bit_array_compare(first, second) { - for (let i = 0; i < first.length; i++) { - if (i >= second.length) { - return new Gt(); // first has more items - } - const f = first.buffer[i]; - const s = second.buffer[i]; - if (f > s) { - return new Gt(); - } - if (f < s) { - return new Lt(); - } - } - // This means that either first did not have any items - // or all items in first were equal to second. - if (first.length === second.length) { - return new Eq(); - } - return new Lt(); // second has more items -} diff --git a/test-output/cases/echo_dict/build/dev/javascript/gleam_version b/test-output/cases/echo_dict/build/dev/javascript/gleam_version deleted file mode 100644 index 3e1ad720b13..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/gleam_version +++ /dev/null @@ -1 +0,0 @@ -1.5.0 \ No newline at end of file diff --git a/test-output/cases/echo_dict/build/dev/javascript/prelude.mjs b/test-output/cases/echo_dict/build/dev/javascript/prelude.mjs deleted file mode 100644 index d2adeef273f..00000000000 --- a/test-output/cases/echo_dict/build/dev/javascript/prelude.mjs +++ /dev/null @@ -1,455 +0,0 @@ -// Values marked with @internal are not part of the public API and may change -// without notice. - -export class CustomType { - withFields(fields) { - let properties = Object.keys(this).map((label) => - label in fields ? fields[label] : this[label], - ); - return new this.constructor(...properties); - } -} - -export class List { - static fromArray(array, tail) { - let t = tail || new Empty(); - for (let i = array.length - 1; i >= 0; --i) { - t = new NonEmpty(array[i], t); - } - return t; - } - - [Symbol.iterator]() { - return new ListIterator(this); - } - - toArray() { - return [...this]; - } - - // @internal - atLeastLength(desired) { - for (let _ of this) { - if (desired <= 0) return true; - desired--; - } - return desired <= 0; - } - - // @internal - hasLength(desired) { - for (let _ of this) { - if (desired <= 0) return false; - desired--; - } - return desired === 0; - } - - // @internal - countLength() { - let length = 0; - for (let _ of this) length++; - return length; - } -} - -// @internal -export function prepend(element, tail) { - return new NonEmpty(element, tail); -} - -export function toList(elements, tail) { - return List.fromArray(elements, tail); -} - -// @internal -class ListIterator { - #current; - - constructor(current) { - this.#current = current; - } - - next() { - if (this.#current instanceof Empty) { - return { done: true }; - } else { - let { head, tail } = this.#current; - this.#current = tail; - return { value: head, done: false }; - } - } -} - -export class Empty extends List {} - -export class NonEmpty extends List { - constructor(head, tail) { - super(); - this.head = head; - this.tail = tail; - } -} - -export class BitArray { - constructor(buffer) { - if (!(buffer instanceof Uint8Array)) { - throw "BitArray can only be constructed from a Uint8Array"; - } - this.buffer = buffer; - } - - // @internal - get length() { - return this.buffer.length; - } - - // @internal - byteAt(index) { - return this.buffer[index]; - } - - // @internal - floatFromSlice(start, end, isBigEndian) { - return byteArrayToFloat(this.buffer, start, end, isBigEndian); - } - - // @internal - intFromSlice(start, end, isBigEndian, isSigned) { - return byteArrayToInt(this.buffer, start, end, isBigEndian, isSigned); - } - - // @internal - binaryFromSlice(start, end) { - return new BitArray(this.buffer.slice(start, end)); - } - - // @internal - sliceAfter(index) { - return new BitArray(this.buffer.slice(index)); - } -} - -export class UtfCodepoint { - constructor(value) { - this.value = value; - } -} - -// @internal -export function toBitArray(segments) { - if (segments.length === 0) { - return new BitArray(new Uint8Array()); - } - - if (segments.length === 1) { - // When there is a single Uint8Array segment, pass it directly to the bit - // array constructor to avoid a copy - if (segments[0] instanceof Uint8Array) { - return new BitArray(segments[0]); - } - - return new BitArray(new Uint8Array(segments)); - } - - // Count the total number of bytes, and check if there are any Uint8Array - // segments - let bytes = 0; - let hasUint8ArraySegment = false; - for (const segment of segments) { - if (segment instanceof Uint8Array) { - bytes += segment.byteLength; - hasUint8ArraySegment = true; - } else { - bytes++; - } - } - - // If there aren't any Uint8Array segments then pass the segments array - // directly to the Uint8Array constructor - if (!hasUint8ArraySegment) { - return new BitArray(new Uint8Array(segments)); - } - - // Copy the segments into a Uint8Array - let u8Array = new Uint8Array(bytes); - let cursor = 0; - for (let segment of segments) { - if (segment instanceof Uint8Array) { - u8Array.set(segment, cursor); - cursor += segment.byteLength; - } else { - u8Array[cursor] = segment; - cursor++; - } - } - - return new BitArray(u8Array); -} - -// @internal -// Derived from this answer https://stackoverflow.com/questions/8482309/converting-javascript-integer-to-byte-array-and-back -export function sizedInt(value, size, isBigEndian) { - if (size < 0) { - return new Uint8Array(); - } - if (size % 8 != 0) { - const msg = `Bit arrays must be byte aligned on JavaScript, got size of ${size} bits`; - throw new globalThis.Error(msg); - } - - const byteArray = new Uint8Array(size / 8); - - // Convert negative number to two's complement representation - if (value < 0) { - value = 2 ** size + value; - } - - if (isBigEndian) { - for (let i = byteArray.length - 1; i >= 0; i--) { - const byte = value % 256; - byteArray[i] = byte; - value = (value - byte) / 256; - } - } else { - for (let i = 0; i < byteArray.length; i++) { - const byte = value % 256; - byteArray[i] = byte; - value = (value - byte) / 256; - } - } - - return byteArray; -} - -// @internal -export function byteArrayToInt(byteArray, start, end, isBigEndian, isSigned) { - let value = 0; - - // Read bytes as an unsigned integer value - if (isBigEndian) { - for (let i = start; i < end; i++) { - value = value * 256 + byteArray[i]; - } - } else { - for (let i = end - 1; i >= start; i--) { - value = value * 256 + byteArray[i]; - } - } - - if (isSigned) { - const byteSize = end - start; - - const highBit = 2 ** (byteSize * 8 - 1); - - // If the high bit is set and this is a signed integer, reinterpret as - // two's complement - if (value >= highBit) { - value -= highBit * 2; - } - } - - return value; -} - -// @internal -export function byteArrayToFloat(byteArray, start, end, isBigEndian) { - const view = new DataView(byteArray.buffer); - - const byteSize = end - start; - - if (byteSize === 8) { - return view.getFloat64(start, !isBigEndian); - } else if (byteSize === 4) { - return view.getFloat32(start, !isBigEndian); - } else { - const msg = `Sized floats must be 32-bit or 64-bit on JavaScript, got size of ${byteSize * 8} bits`; - throw new globalThis.Error(msg); - } -} - -// @internal -export function stringBits(string) { - return new TextEncoder().encode(string); -} - -// @internal -export function codepointBits(codepoint) { - return stringBits(String.fromCodePoint(codepoint.value)); -} - -// @internal -export function sizedFloat(float, size, isBigEndian) { - if (size !== 32 && size !== 64) { - const msg = `Sized floats must be 32-bit or 64-bit on JavaScript, got size of ${size} bits`; - throw new globalThis.Error(msg); - } - - const byteArray = new Uint8Array(size / 8); - - const view = new DataView(byteArray.buffer); - - if (size == 64) { - view.setFloat64(0, float, !isBigEndian); - } else if (size === 32) { - view.setFloat32(0, float, !isBigEndian); - } - - return byteArray; -} - -export class Result extends CustomType { - // @internal - static isResult(data) { - return data instanceof Result; - } -} - -export class Ok extends Result { - constructor(value) { - super(); - this[0] = value; - } - - // @internal - isOk() { - return true; - } -} - -export class Error extends Result { - constructor(detail) { - super(); - this[0] = detail; - } - - // @internal - isOk() { - return false; - } -} - -export function isEqual(x, y) { - let values = [x, y]; - - while (values.length) { - let a = values.pop(); - let b = values.pop(); - if (a === b) continue; - - if (!isObject(a) || !isObject(b)) return false; - let unequal = - !structurallyCompatibleObjects(a, b) || - unequalDates(a, b) || - unequalBuffers(a, b) || - unequalArrays(a, b) || - unequalMaps(a, b) || - unequalSets(a, b) || - unequalRegExps(a, b); - if (unequal) return false; - - const proto = Object.getPrototypeOf(a); - if (proto !== null && typeof proto.equals === "function") { - try { - if (a.equals(b)) continue; - else return false; - } catch {} - } - - let [keys, get] = getters(a); - for (let k of keys(a)) { - values.push(get(a, k), get(b, k)); - } - } - - return true; -} - -function getters(object) { - if (object instanceof Map) { - return [(x) => x.keys(), (x, y) => x.get(y)]; - } else { - let extra = object instanceof globalThis.Error ? ["message"] : []; - return [(x) => [...extra, ...Object.keys(x)], (x, y) => x[y]]; - } -} - -function unequalDates(a, b) { - return a instanceof Date && (a > b || a < b); -} - -function unequalBuffers(a, b) { - return ( - a.buffer instanceof ArrayBuffer && - a.BYTES_PER_ELEMENT && - !(a.byteLength === b.byteLength && a.every((n, i) => n === b[i])) - ); -} - -function unequalArrays(a, b) { - return Array.isArray(a) && a.length !== b.length; -} - -function unequalMaps(a, b) { - return a instanceof Map && a.size !== b.size; -} - -function unequalSets(a, b) { - return ( - a instanceof Set && (a.size != b.size || [...a].some((e) => !b.has(e))) - ); -} - -function unequalRegExps(a, b) { - return a instanceof RegExp && (a.source !== b.source || a.flags !== b.flags); -} - -function isObject(a) { - return typeof a === "object" && a !== null; -} - -function structurallyCompatibleObjects(a, b) { - if (typeof a !== "object" && typeof b !== "object" && (!a || !b)) - return false; - - let nonstructural = [Promise, WeakSet, WeakMap, Function]; - if (nonstructural.some((c) => a instanceof c)) return false; - - return a.constructor === b.constructor; -} - -// @internal -export function remainderInt(a, b) { - if (b === 0) { - return 0; - } else { - return a % b; - } -} - -// @internal -export function divideInt(a, b) { - return Math.trunc(divideFloat(a, b)); -} - -// @internal -export function divideFloat(a, b) { - if (b === 0) { - return 0; - } else { - return a / b; - } -} - -// @internal -export function makeError(variant, module, line, fn, message, extra) { - let error = new globalThis.Error(message); - error.gleam_error = variant; - error.module = module; - error.line = line; - error.function = fn; - // TODO: Remove this with Gleam v2.0.0 - error.fn = fn; - for (let k in extra) error[k] = extra[k]; - return error; -} diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/LICENCE b/test-output/cases/echo_dict/build/packages/gleam_stdlib/LICENCE deleted file mode 100644 index c1dabd08e3d..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/LICENCE +++ /dev/null @@ -1,191 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Copyright 2018, Louis Pilfold . - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/README.md b/test-output/cases/echo_dict/build/packages/gleam_stdlib/README.md deleted file mode 100644 index bb5f4d344e6..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/README.md +++ /dev/null @@ -1,39 +0,0 @@ -# stdlib - -GitHub release -Discord chat -![CI](https://github.com/gleam-lang/stdlib/workflows/CI/badge.svg?branch=main) - -Gleam's standard library! -Documentation available on [HexDocs](https://hexdocs.pm/gleam_stdlib/). - -## Installation - -Add `gleam_stdlib` to your Gleam project. - -```sh -gleam add gleam_stdlib -``` - -## Usage - -Import the modules you want to use and write some code! - -```gleam -import gleam/string - -pub fn greet(name: String) -> String { - string.concat(["Hello ", name, "!"]) -} -``` - -## Targets - -Gleam's standard library supports both targets: Erlang and JavaScript. - -### Compatibility - -This library is compatible with all versions of Erlang/OTP 26 and higher, -as well as all NodeJS, Deno, Bun, and major browsers that are currently -supported by their maintainers. If you have a compatibility issue with -any platform open an issue and we'll see what we can do to help. diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/gleam.toml b/test-output/cases/echo_dict/build/packages/gleam_stdlib/gleam.toml deleted file mode 100644 index 6f4c8878549..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/gleam.toml +++ /dev/null @@ -1,16 +0,0 @@ -name = "gleam_stdlib" -version = "0.41.0" -gleam = ">= 0.32.0" -licences = ["Apache-2.0"] -description = "A standard library for the Gleam programming language" - -repository = { type = "github", user = "gleam-lang", repo = "stdlib" } -links = [ - { title = "Website", href = "https://gleam.run" }, - { title = "Sponsor", href = "https://github.com/sponsors/lpil" }, -] - -[javascript.deno] -allow_read = [ - "./", -] diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/include/gleam@dynamic_DecodeError.hrl b/test-output/cases/echo_dict/build/packages/gleam_stdlib/include/gleam@dynamic_DecodeError.hrl deleted file mode 100644 index b1135f2dea0..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/include/gleam@dynamic_DecodeError.hrl +++ /dev/null @@ -1,5 +0,0 @@ --record(decode_error, { - expected :: binary(), - found :: binary(), - path :: list(binary()) -}). diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/include/gleam@iterator_Iterator.hrl b/test-output/cases/echo_dict/build/packages/gleam_stdlib/include/gleam@iterator_Iterator.hrl deleted file mode 100644 index b0d08dc71a3..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/include/gleam@iterator_Iterator.hrl +++ /dev/null @@ -1 +0,0 @@ --record(iterator, {continuation :: fun(() -> gleam@iterator:action(any()))}). diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/include/gleam@iterator_Next.hrl b/test-output/cases/echo_dict/build/packages/gleam_stdlib/include/gleam@iterator_Next.hrl deleted file mode 100644 index 1f61922beda..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/include/gleam@iterator_Next.hrl +++ /dev/null @@ -1 +0,0 @@ --record(next, {element :: any(), accumulator :: any()}). diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/include/gleam@queue_Queue.hrl b/test-output/cases/echo_dict/build/packages/gleam_stdlib/include/gleam@queue_Queue.hrl deleted file mode 100644 index 88ac25ed0a7..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/include/gleam@queue_Queue.hrl +++ /dev/null @@ -1 +0,0 @@ --record(queue, {in :: list(any()), out :: list(any())}). diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/include/gleam@regex_CompileError.hrl b/test-output/cases/echo_dict/build/packages/gleam_stdlib/include/gleam@regex_CompileError.hrl deleted file mode 100644 index ad5511eb103..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/include/gleam@regex_CompileError.hrl +++ /dev/null @@ -1 +0,0 @@ --record(compile_error, {error :: binary(), byte_index :: integer()}). diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/include/gleam@regex_Match.hrl b/test-output/cases/echo_dict/build/packages/gleam_stdlib/include/gleam@regex_Match.hrl deleted file mode 100644 index 42166198699..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/include/gleam@regex_Match.hrl +++ /dev/null @@ -1,4 +0,0 @@ --record(match, { - content :: binary(), - submatches :: list(gleam@option:option(binary())) -}). diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/include/gleam@regex_Options.hrl b/test-output/cases/echo_dict/build/packages/gleam_stdlib/include/gleam@regex_Options.hrl deleted file mode 100644 index 0074603b961..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/include/gleam@regex_Options.hrl +++ /dev/null @@ -1 +0,0 @@ --record(options, {case_insensitive :: boolean(), multi_line :: boolean()}). diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/include/gleam@set_Set.hrl b/test-output/cases/echo_dict/build/packages/gleam_stdlib/include/gleam@set_Set.hrl deleted file mode 100644 index 51fb7787567..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/include/gleam@set_Set.hrl +++ /dev/null @@ -1 +0,0 @@ --record(set, {dict :: gleam@dict:dict(any(), list(nil))}). diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/include/gleam@uri_Uri.hrl b/test-output/cases/echo_dict/build/packages/gleam_stdlib/include/gleam@uri_Uri.hrl deleted file mode 100644 index 50150f476b1..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/include/gleam@uri_Uri.hrl +++ /dev/null @@ -1,9 +0,0 @@ --record(uri, { - scheme :: gleam@option:option(binary()), - userinfo :: gleam@option:option(binary()), - host :: gleam@option:option(binary()), - port :: gleam@option:option(integer()), - path :: binary(), - 'query' :: gleam@option:option(binary()), - fragment :: gleam@option:option(binary()) -}). diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/dict.mjs b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/dict.mjs deleted file mode 100644 index a8309e0cdbd..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/dict.mjs +++ /dev/null @@ -1,957 +0,0 @@ -/** - * This file uses jsdoc to annotate types. - * These types can be checked using the typescript compiler with "checkjs" option. - */ - -import { isEqual } from "./gleam.mjs"; - -const referenceMap = new WeakMap(); -const tempDataView = new DataView(new ArrayBuffer(8)); -let referenceUID = 0; -/** - * hash the object by reference using a weak map and incrementing uid - * @param {any} o - * @returns {number} - */ -function hashByReference(o) { - const known = referenceMap.get(o); - if (known !== undefined) { - return known; - } - const hash = referenceUID++; - if (referenceUID === 0x7fffffff) { - referenceUID = 0; - } - referenceMap.set(o, hash); - return hash; -} -/** - * merge two hashes in an order sensitive way - * @param {number} a - * @param {number} b - * @returns {number} - */ -function hashMerge(a, b) { - return (a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2))) | 0; -} -/** - * standard string hash popularised by java - * @param {string} s - * @returns {number} - */ -function hashString(s) { - let hash = 0; - const len = s.length; - for (let i = 0; i < len; i++) { - hash = (Math.imul(31, hash) + s.charCodeAt(i)) | 0; - } - return hash; -} -/** - * hash a number by converting to two integers and do some jumbling - * @param {number} n - * @returns {number} - */ -function hashNumber(n) { - tempDataView.setFloat64(0, n); - const i = tempDataView.getInt32(0); - const j = tempDataView.getInt32(4); - return Math.imul(0x45d9f3b, (i >> 16) ^ i) ^ j; -} -/** - * hash a BigInt by converting it to a string and hashing that - * @param {BigInt} n - * @returns {number} - */ -function hashBigInt(n) { - return hashString(n.toString()); -} -/** - * hash any js object - * @param {any} o - * @returns {number} - */ -function hashObject(o) { - const proto = Object.getPrototypeOf(o); - if (proto !== null && typeof proto.hashCode === "function") { - try { - const code = o.hashCode(o); - if (typeof code === "number") { - return code; - } - } catch {} - } - if (o instanceof Promise || o instanceof WeakSet || o instanceof WeakMap) { - return hashByReference(o); - } - if (o instanceof Date) { - return hashNumber(o.getTime()); - } - let h = 0; - if (o instanceof ArrayBuffer) { - o = new Uint8Array(o); - } - if (Array.isArray(o) || o instanceof Uint8Array) { - for (let i = 0; i < o.length; i++) { - h = (Math.imul(31, h) + getHash(o[i])) | 0; - } - } else if (o instanceof Set) { - o.forEach((v) => { - h = (h + getHash(v)) | 0; - }); - } else if (o instanceof Map) { - o.forEach((v, k) => { - h = (h + hashMerge(getHash(v), getHash(k))) | 0; - }); - } else { - const keys = Object.keys(o); - for (let i = 0; i < keys.length; i++) { - const k = keys[i]; - const v = o[k]; - h = (h + hashMerge(getHash(v), hashString(k))) | 0; - } - } - return h; -} -/** - * hash any js value - * @param {any} u - * @returns {number} - */ -export function getHash(u) { - if (u === null) return 0x42108422; - if (u === undefined) return 0x42108423; - if (u === true) return 0x42108421; - if (u === false) return 0x42108420; - switch (typeof u) { - case "number": - return hashNumber(u); - case "string": - return hashString(u); - case "bigint": - return hashBigInt(u); - case "object": - return hashObject(u); - case "symbol": - return hashByReference(u); - case "function": - return hashByReference(u); - default: - return 0; // should be unreachable - } -} -/** - * @template K,V - * @typedef {ArrayNode | IndexNode | CollisionNode} Node - */ -/** - * @template K,V - * @typedef {{ type: typeof ENTRY, k: K, v: V }} Entry - */ -/** - * @template K,V - * @typedef {{ type: typeof ARRAY_NODE, size: number, array: (undefined | Entry | Node)[] }} ArrayNode - */ -/** - * @template K,V - * @typedef {{ type: typeof INDEX_NODE, bitmap: number, array: (Entry | Node)[] }} IndexNode - */ -/** - * @template K,V - * @typedef {{ type: typeof COLLISION_NODE, hash: number, array: Entry[] }} CollisionNode - */ -/** - * @typedef {{ val: boolean }} Flag - */ -const SHIFT = 5; // number of bits you need to shift by to get the next bucket -const BUCKET_SIZE = Math.pow(2, SHIFT); -const MASK = BUCKET_SIZE - 1; // used to zero out all bits not in the bucket -const MAX_INDEX_NODE = BUCKET_SIZE / 2; // when does index node grow into array node -const MIN_ARRAY_NODE = BUCKET_SIZE / 4; // when does array node shrink to index node -const ENTRY = 0; -const ARRAY_NODE = 1; -const INDEX_NODE = 2; -const COLLISION_NODE = 3; -/** @type {IndexNode} */ -const EMPTY = { - type: INDEX_NODE, - bitmap: 0, - array: [], -}; -/** - * Mask the hash to get only the bucket corresponding to shift - * @param {number} hash - * @param {number} shift - * @returns {number} - */ -function mask(hash, shift) { - return (hash >>> shift) & MASK; -} -/** - * Set only the Nth bit where N is the masked hash - * @param {number} hash - * @param {number} shift - * @returns {number} - */ -function bitpos(hash, shift) { - return 1 << mask(hash, shift); -} -/** - * Count the number of 1 bits in a number - * @param {number} x - * @returns {number} - */ -function bitcount(x) { - x -= (x >> 1) & 0x55555555; - x = (x & 0x33333333) + ((x >> 2) & 0x33333333); - x = (x + (x >> 4)) & 0x0f0f0f0f; - x += x >> 8; - x += x >> 16; - return x & 0x7f; -} -/** - * Calculate the array index of an item in a bitmap index node - * @param {number} bitmap - * @param {number} bit - * @returns {number} - */ -function index(bitmap, bit) { - return bitcount(bitmap & (bit - 1)); -} -/** - * Efficiently copy an array and set one value at an index - * @template T - * @param {T[]} arr - * @param {number} at - * @param {T} val - * @returns {T[]} - */ -function cloneAndSet(arr, at, val) { - const len = arr.length; - const out = new Array(len); - for (let i = 0; i < len; ++i) { - out[i] = arr[i]; - } - out[at] = val; - return out; -} -/** - * Efficiently copy an array and insert one value at an index - * @template T - * @param {T[]} arr - * @param {number} at - * @param {T} val - * @returns {T[]} - */ -function spliceIn(arr, at, val) { - const len = arr.length; - const out = new Array(len + 1); - let i = 0; - let g = 0; - while (i < at) { - out[g++] = arr[i++]; - } - out[g++] = val; - while (i < len) { - out[g++] = arr[i++]; - } - return out; -} -/** - * Efficiently copy an array and remove one value at an index - * @template T - * @param {T[]} arr - * @param {number} at - * @returns {T[]} - */ -function spliceOut(arr, at) { - const len = arr.length; - const out = new Array(len - 1); - let i = 0; - let g = 0; - while (i < at) { - out[g++] = arr[i++]; - } - ++i; - while (i < len) { - out[g++] = arr[i++]; - } - return out; -} -/** - * Create a new node containing two entries - * @template K,V - * @param {number} shift - * @param {K} key1 - * @param {V} val1 - * @param {number} key2hash - * @param {K} key2 - * @param {V} val2 - * @returns {Node} - */ -function createNode(shift, key1, val1, key2hash, key2, val2) { - const key1hash = getHash(key1); - if (key1hash === key2hash) { - return { - type: COLLISION_NODE, - hash: key1hash, - array: [ - { type: ENTRY, k: key1, v: val1 }, - { type: ENTRY, k: key2, v: val2 }, - ], - }; - } - const addedLeaf = { val: false }; - return assoc( - assocIndex(EMPTY, shift, key1hash, key1, val1, addedLeaf), - shift, - key2hash, - key2, - val2, - addedLeaf - ); -} -/** - * @template T,K,V - * @callback AssocFunction - * @param {T} root - * @param {number} shift - * @param {number} hash - * @param {K} key - * @param {V} val - * @param {Flag} addedLeaf - * @returns {Node} - */ -/** - * Associate a node with a new entry, creating a new node - * @template T,K,V - * @type {AssocFunction,K,V>} - */ -function assoc(root, shift, hash, key, val, addedLeaf) { - switch (root.type) { - case ARRAY_NODE: - return assocArray(root, shift, hash, key, val, addedLeaf); - case INDEX_NODE: - return assocIndex(root, shift, hash, key, val, addedLeaf); - case COLLISION_NODE: - return assocCollision(root, shift, hash, key, val, addedLeaf); - } -} -/** - * @template T,K,V - * @type {AssocFunction,K,V>} - */ -function assocArray(root, shift, hash, key, val, addedLeaf) { - const idx = mask(hash, shift); - const node = root.array[idx]; - // if the corresponding index is empty set the index to a newly created node - if (node === undefined) { - addedLeaf.val = true; - return { - type: ARRAY_NODE, - size: root.size + 1, - array: cloneAndSet(root.array, idx, { type: ENTRY, k: key, v: val }), - }; - } - if (node.type === ENTRY) { - // if keys are equal replace the entry - if (isEqual(key, node.k)) { - if (val === node.v) { - return root; - } - return { - type: ARRAY_NODE, - size: root.size, - array: cloneAndSet(root.array, idx, { - type: ENTRY, - k: key, - v: val, - }), - }; - } - // otherwise upgrade the entry to a node and insert - addedLeaf.val = true; - return { - type: ARRAY_NODE, - size: root.size, - array: cloneAndSet( - root.array, - idx, - createNode(shift + SHIFT, node.k, node.v, hash, key, val) - ), - }; - } - // otherwise call assoc on the child node - const n = assoc(node, shift + SHIFT, hash, key, val, addedLeaf); - // if the child node hasn't changed just return the old root - if (n === node) { - return root; - } - // otherwise set the index to the new node - return { - type: ARRAY_NODE, - size: root.size, - array: cloneAndSet(root.array, idx, n), - }; -} -/** - * @template T,K,V - * @type {AssocFunction,K,V>} - */ -function assocIndex(root, shift, hash, key, val, addedLeaf) { - const bit = bitpos(hash, shift); - const idx = index(root.bitmap, bit); - // if there is already a item at this hash index.. - if ((root.bitmap & bit) !== 0) { - // if there is a node at the index (not an entry), call assoc on the child node - const node = root.array[idx]; - if (node.type !== ENTRY) { - const n = assoc(node, shift + SHIFT, hash, key, val, addedLeaf); - if (n === node) { - return root; - } - return { - type: INDEX_NODE, - bitmap: root.bitmap, - array: cloneAndSet(root.array, idx, n), - }; - } - // otherwise there is an entry at the index - // if the keys are equal replace the entry with the updated value - const nodeKey = node.k; - if (isEqual(key, nodeKey)) { - if (val === node.v) { - return root; - } - return { - type: INDEX_NODE, - bitmap: root.bitmap, - array: cloneAndSet(root.array, idx, { - type: ENTRY, - k: key, - v: val, - }), - }; - } - // if the keys are not equal, replace the entry with a new child node - addedLeaf.val = true; - return { - type: INDEX_NODE, - bitmap: root.bitmap, - array: cloneAndSet( - root.array, - idx, - createNode(shift + SHIFT, nodeKey, node.v, hash, key, val) - ), - }; - } else { - // else there is currently no item at the hash index - const n = root.array.length; - // if the number of nodes is at the maximum, expand this node into an array node - if (n >= MAX_INDEX_NODE) { - // create a 32 length array for the new array node (one for each bit in the hash) - const nodes = new Array(32); - // create and insert a node for the new entry - const jdx = mask(hash, shift); - nodes[jdx] = assocIndex(EMPTY, shift + SHIFT, hash, key, val, addedLeaf); - let j = 0; - let bitmap = root.bitmap; - // place each item in the index node into the correct spot in the array node - // loop through all 32 bits / array positions - for (let i = 0; i < 32; i++) { - if ((bitmap & 1) !== 0) { - const node = root.array[j++]; - nodes[i] = node; - } - // shift the bitmap to process the next bit - bitmap = bitmap >>> 1; - } - return { - type: ARRAY_NODE, - size: n + 1, - array: nodes, - }; - } else { - // else there is still space in this index node - // simply insert a new entry at the hash index - const newArray = spliceIn(root.array, idx, { - type: ENTRY, - k: key, - v: val, - }); - addedLeaf.val = true; - return { - type: INDEX_NODE, - bitmap: root.bitmap | bit, - array: newArray, - }; - } - } -} -/** - * @template T,K,V - * @type {AssocFunction,K,V>} - */ -function assocCollision(root, shift, hash, key, val, addedLeaf) { - // if there is a hash collision - if (hash === root.hash) { - const idx = collisionIndexOf(root, key); - // if this key already exists replace the entry with the new value - if (idx !== -1) { - const entry = root.array[idx]; - if (entry.v === val) { - return root; - } - return { - type: COLLISION_NODE, - hash: hash, - array: cloneAndSet(root.array, idx, { type: ENTRY, k: key, v: val }), - }; - } - // otherwise insert the entry at the end of the array - const size = root.array.length; - addedLeaf.val = true; - return { - type: COLLISION_NODE, - hash: hash, - array: cloneAndSet(root.array, size, { type: ENTRY, k: key, v: val }), - }; - } - // if there is no hash collision, upgrade to an index node - return assoc( - { - type: INDEX_NODE, - bitmap: bitpos(root.hash, shift), - array: [root], - }, - shift, - hash, - key, - val, - addedLeaf - ); -} -/** - * Find the index of a key in the collision node's array - * @template K,V - * @param {CollisionNode} root - * @param {K} key - * @returns {number} - */ -function collisionIndexOf(root, key) { - const size = root.array.length; - for (let i = 0; i < size; i++) { - if (isEqual(key, root.array[i].k)) { - return i; - } - } - return -1; -} -/** - * @template T,K,V - * @callback FindFunction - * @param {T} root - * @param {number} shift - * @param {number} hash - * @param {K} key - * @returns {undefined | Entry} - */ -/** - * Return the found entry or undefined if not present in the root - * @template K,V - * @type {FindFunction,K,V>} - */ -function find(root, shift, hash, key) { - switch (root.type) { - case ARRAY_NODE: - return findArray(root, shift, hash, key); - case INDEX_NODE: - return findIndex(root, shift, hash, key); - case COLLISION_NODE: - return findCollision(root, key); - } -} -/** - * @template K,V - * @type {FindFunction,K,V>} - */ -function findArray(root, shift, hash, key) { - const idx = mask(hash, shift); - const node = root.array[idx]; - if (node === undefined) { - return undefined; - } - if (node.type !== ENTRY) { - return find(node, shift + SHIFT, hash, key); - } - if (isEqual(key, node.k)) { - return node; - } - return undefined; -} -/** - * @template K,V - * @type {FindFunction,K,V>} - */ -function findIndex(root, shift, hash, key) { - const bit = bitpos(hash, shift); - if ((root.bitmap & bit) === 0) { - return undefined; - } - const idx = index(root.bitmap, bit); - const node = root.array[idx]; - if (node.type !== ENTRY) { - return find(node, shift + SHIFT, hash, key); - } - if (isEqual(key, node.k)) { - return node; - } - return undefined; -} -/** - * @template K,V - * @param {CollisionNode} root - * @param {K} key - * @returns {undefined | Entry} - */ -function findCollision(root, key) { - const idx = collisionIndexOf(root, key); - if (idx < 0) { - return undefined; - } - return root.array[idx]; -} -/** - * @template T,K,V - * @callback WithoutFunction - * @param {T} root - * @param {number} shift - * @param {number} hash - * @param {K} key - * @returns {undefined | Node} - */ -/** - * Remove an entry from the root, returning the updated root. - * Returns undefined if the node should be removed from the parent. - * @template K,V - * @type {WithoutFunction,K,V>} - * */ -function without(root, shift, hash, key) { - switch (root.type) { - case ARRAY_NODE: - return withoutArray(root, shift, hash, key); - case INDEX_NODE: - return withoutIndex(root, shift, hash, key); - case COLLISION_NODE: - return withoutCollision(root, key); - } -} -/** - * @template K,V - * @type {WithoutFunction,K,V>} - */ -function withoutArray(root, shift, hash, key) { - const idx = mask(hash, shift); - const node = root.array[idx]; - if (node === undefined) { - return root; // already empty - } - let n = undefined; - // if node is an entry and the keys are not equal there is nothing to remove - // if node is not an entry do a recursive call - if (node.type === ENTRY) { - if (!isEqual(node.k, key)) { - return root; // no changes - } - } else { - n = without(node, shift + SHIFT, hash, key); - if (n === node) { - return root; // no changes - } - } - // if the recursive call returned undefined the node should be removed - if (n === undefined) { - // if the number of child nodes is at the minimum, pack into an index node - if (root.size <= MIN_ARRAY_NODE) { - const arr = root.array; - const out = new Array(root.size - 1); - let i = 0; - let j = 0; - let bitmap = 0; - while (i < idx) { - const nv = arr[i]; - if (nv !== undefined) { - out[j] = nv; - bitmap |= 1 << i; - ++j; - } - ++i; - } - ++i; // skip copying the removed node - while (i < arr.length) { - const nv = arr[i]; - if (nv !== undefined) { - out[j] = nv; - bitmap |= 1 << i; - ++j; - } - ++i; - } - return { - type: INDEX_NODE, - bitmap: bitmap, - array: out, - }; - } - return { - type: ARRAY_NODE, - size: root.size - 1, - array: cloneAndSet(root.array, idx, n), - }; - } - return { - type: ARRAY_NODE, - size: root.size, - array: cloneAndSet(root.array, idx, n), - }; -} -/** - * @template K,V - * @type {WithoutFunction,K,V>} - */ -function withoutIndex(root, shift, hash, key) { - const bit = bitpos(hash, shift); - if ((root.bitmap & bit) === 0) { - return root; // already empty - } - const idx = index(root.bitmap, bit); - const node = root.array[idx]; - // if the item is not an entry - if (node.type !== ENTRY) { - const n = without(node, shift + SHIFT, hash, key); - if (n === node) { - return root; // no changes - } - // if not undefined, the child node still has items, so update it - if (n !== undefined) { - return { - type: INDEX_NODE, - bitmap: root.bitmap, - array: cloneAndSet(root.array, idx, n), - }; - } - // otherwise the child node should be removed - // if it was the only child node, remove this node from the parent - if (root.bitmap === bit) { - return undefined; - } - // otherwise just remove the child node - return { - type: INDEX_NODE, - bitmap: root.bitmap ^ bit, - array: spliceOut(root.array, idx), - }; - } - // otherwise the item is an entry, remove it if the key matches - if (isEqual(key, node.k)) { - if (root.bitmap === bit) { - return undefined; - } - return { - type: INDEX_NODE, - bitmap: root.bitmap ^ bit, - array: spliceOut(root.array, idx), - }; - } - return root; -} -/** - * @template K,V - * @param {CollisionNode} root - * @param {K} key - * @returns {undefined | Node} - */ -function withoutCollision(root, key) { - const idx = collisionIndexOf(root, key); - // if the key not found, no changes - if (idx < 0) { - return root; - } - // otherwise the entry was found, remove it - // if it was the only entry in this node, remove the whole node - if (root.array.length === 1) { - return undefined; - } - // otherwise just remove the entry - return { - type: COLLISION_NODE, - hash: root.hash, - array: spliceOut(root.array, idx), - }; -} -/** - * @template K,V - * @param {undefined | Node} root - * @param {(value:V,key:K)=>void} fn - * @returns {void} - */ -function forEach(root, fn) { - if (root === undefined) { - return; - } - const items = root.array; - const size = items.length; - for (let i = 0; i < size; i++) { - const item = items[i]; - if (item === undefined) { - continue; - } - if (item.type === ENTRY) { - fn(item.v, item.k); - continue; - } - forEach(item, fn); - } -} -/** - * Extra wrapper to keep track of Dict size and clean up the API - * @template K,V - */ -export default class Dict { - /** - * @template V - * @param {Record} o - * @returns {Dict} - */ - static fromObject(o) { - const keys = Object.keys(o); - /** @type Dict */ - let m = Dict.new(); - for (let i = 0; i < keys.length; i++) { - const k = keys[i]; - m = m.set(k, o[k]); - } - return m; - } - /** - * @template K,V - * @param {Map} o - * @returns {Dict} - */ - static fromMap(o) { - /** @type Dict */ - let m = Dict.new(); - o.forEach((v, k) => { - m = m.set(k, v); - }); - return m; - } - static new() { - return new Dict(undefined, 0); - } - /** - * @param {undefined | Node} root - * @param {number} size - */ - constructor(root, size) { - this.root = root; - this.size = size; - } - /** - * @template NotFound - * @param {K} key - * @param {NotFound} notFound - * @returns {NotFound | V} - */ - get(key, notFound) { - if (this.root === undefined) { - return notFound; - } - const found = find(this.root, 0, getHash(key), key); - if (found === undefined) { - return notFound; - } - return found.v; - } - /** - * @param {K} key - * @param {V} val - * @returns {Dict} - */ - set(key, val) { - const addedLeaf = { val: false }; - const root = this.root === undefined ? EMPTY : this.root; - const newRoot = assoc(root, 0, getHash(key), key, val, addedLeaf); - if (newRoot === this.root) { - return this; - } - return new Dict(newRoot, addedLeaf.val ? this.size + 1 : this.size); - } - /** - * @param {K} key - * @returns {Dict} - */ - delete(key) { - if (this.root === undefined) { - return this; - } - const newRoot = without(this.root, 0, getHash(key), key); - if (newRoot === this.root) { - return this; - } - if (newRoot === undefined) { - return Dict.new(); - } - return new Dict(newRoot, this.size - 1); - } - /** - * @param {K} key - * @returns {boolean} - */ - has(key) { - if (this.root === undefined) { - return false; - } - return find(this.root, 0, getHash(key), key) !== undefined; - } - /** - * @returns {[K,V][]} - */ - entries() { - if (this.root === undefined) { - return []; - } - /** @type [K,V][] */ - const result = []; - this.forEach((v, k) => result.push([k, v])); - return result; - } - /** - * - * @param {(val:V,key:K)=>void} fn - */ - forEach(fn) { - forEach(this.root, fn); - } - hashCode() { - let h = 0; - this.forEach((v, k) => { - h = (h + hashMerge(getHash(v), getHash(k))) | 0; - }); - return h; - } - /** - * @param {unknown} o - * @returns {boolean} - */ - equals(o) { - if (!(o instanceof Dict) || this.size !== o.size) { - return false; - } - let equal = true; - this.forEach((v, k) => { - equal = equal && isEqual(o.get(k, !v), v); - }); - return equal; - } -} diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bit_array.gleam b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bit_array.gleam deleted file mode 100644 index 14db9027505..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bit_array.gleam +++ /dev/null @@ -1,238 +0,0 @@ -//// BitArrays are a sequence of binary data of any length. - -import gleam/int -import gleam/order -import gleam/string - -/// Converts a UTF-8 `String` type into a `BitArray`. -/// -@external(erlang, "gleam_stdlib", "identity") -@external(javascript, "../gleam_stdlib.mjs", "bit_array_from_string") -pub fn from_string(x: String) -> BitArray - -/// Returns an integer which is the number of bytes in the bit array. -/// -@external(erlang, "erlang", "byte_size") -@external(javascript, "../gleam_stdlib.mjs", "length") -pub fn byte_size(x: BitArray) -> Int - -/// Creates a new bit array by joining two bit arrays. -/// -/// ## Examples -/// -/// ```gleam -/// append(to: from_string("butter"), suffix: from_string("fly")) -/// // -> from_string("butterfly") -/// ``` -/// -pub fn append(to first: BitArray, suffix second: BitArray) -> BitArray { - concat([first, second]) -} - -/// Extracts a sub-section of a bit array. -/// -/// The slice will start at given position and continue up to specified -/// length. -/// A negative length can be used to extract bytes at the end of a bit array. -/// -/// This function runs in constant time. -/// -@external(erlang, "gleam_stdlib", "bit_array_slice") -@external(javascript, "../gleam_stdlib.mjs", "bit_array_slice") -pub fn slice( - from string: BitArray, - at position: Int, - take length: Int, -) -> Result(BitArray, Nil) - -/// Tests to see whether a bit array is valid UTF-8. -/// -pub fn is_utf8(bits: BitArray) -> Bool { - do_is_utf8(bits) -} - -@target(erlang) -fn do_is_utf8(bits: BitArray) -> Bool { - case bits { - <<>> -> True - <<_:utf8, rest:bytes>> -> do_is_utf8(rest) - _ -> False - } -} - -@target(javascript) -fn do_is_utf8(bits: BitArray) -> Bool { - case to_string(bits) { - Ok(_) -> True - _ -> False - } -} - -/// Converts a bit array to a string. -/// -/// Returns an error if the bit array is invalid UTF-8 data. -/// -pub fn to_string(bits: BitArray) -> Result(String, Nil) { - do_to_string(bits) -} - -@external(erlang, "gleam_stdlib", "identity") -fn unsafe_to_string(a: BitArray) -> String - -@external(javascript, "../gleam_stdlib.mjs", "bit_array_to_string") -fn do_to_string(bits: BitArray) -> Result(String, Nil) { - case is_utf8(bits) { - True -> Ok(unsafe_to_string(bits)) - False -> Error(Nil) - } -} - -/// Creates a new bit array by joining multiple binaries. -/// -/// ## Examples -/// -/// ```gleam -/// concat([from_string("butter"), from_string("fly")]) -/// // -> from_string("butterfly") -/// ``` -/// -@external(erlang, "gleam_stdlib", "bit_array_concat") -@external(javascript, "../gleam_stdlib.mjs", "bit_array_concat") -pub fn concat(bit_arrays: List(BitArray)) -> BitArray - -/// Encodes a BitArray into a base 64 encoded string. -/// -@external(erlang, "gleam_stdlib", "bit_array_base64_encode") -@external(javascript, "../gleam_stdlib.mjs", "encode64") -pub fn base64_encode(input: BitArray, padding: Bool) -> String - -/// Decodes a base 64 encoded string into a `BitArray`. -/// -pub fn base64_decode(encoded: String) -> Result(BitArray, Nil) { - let padded = case byte_size(from_string(encoded)) % 4 { - 0 -> encoded - n -> string.append(encoded, string.repeat("=", 4 - n)) - } - decode64(padded) -} - -@external(erlang, "gleam_stdlib", "base_decode64") -@external(javascript, "../gleam_stdlib.mjs", "decode64") -fn decode64(a: String) -> Result(BitArray, Nil) - -/// Encodes a `BitArray` into a base 64 encoded string with URL and filename safe alphabet. -/// -pub fn base64_url_encode(input: BitArray, padding: Bool) -> String { - base64_encode(input, padding) - |> string.replace("+", "-") - |> string.replace("/", "_") -} - -/// Decodes a base 64 encoded string with URL and filename safe alphabet into a `BitArray`. -/// -pub fn base64_url_decode(encoded: String) -> Result(BitArray, Nil) { - encoded - |> string.replace("-", "+") - |> string.replace("_", "/") - |> base64_decode() -} - -@external(erlang, "binary", "encode_hex") -@external(javascript, "../gleam_stdlib.mjs", "base16_encode") -pub fn base16_encode(input: BitArray) -> String - -@external(erlang, "gleam_stdlib", "base16_decode") -@external(javascript, "../gleam_stdlib.mjs", "base16_decode") -pub fn base16_decode(input: String) -> Result(BitArray, Nil) - -/// Converts a bit array to a string containing the decimal value of each byte. -/// -/// ## Examples -/// -/// ```gleam -/// inspect(<<0, 20, 0x20, 255>>) -/// // -> "<<0, 20, 32, 255>>" -/// -/// inspect(<<100, 5:3>>) -/// // -> "<<100, 5:size(3)>>" -/// ``` -/// -pub fn inspect(input: BitArray) -> String { - do_inspect(input, "<<") <> ">>" -} - -@external(javascript, "../gleam_stdlib.mjs", "bit_array_inspect") -fn do_inspect(input: BitArray, accumulator: String) -> String { - case input { - <<>> -> accumulator - - <> -> accumulator <> int.to_string(x) <> ":size(1)" - <> -> accumulator <> int.to_string(x) <> ":size(2)" - <> -> accumulator <> int.to_string(x) <> ":size(3)" - <> -> accumulator <> int.to_string(x) <> ":size(4)" - <> -> accumulator <> int.to_string(x) <> ":size(5)" - <> -> accumulator <> int.to_string(x) <> ":size(6)" - <> -> accumulator <> int.to_string(x) <> ":size(7)" - - <> -> { - let suffix = case rest { - <<>> -> "" - _ -> ", " - } - - let accumulator = accumulator <> int.to_string(x) <> suffix - - do_inspect(rest, accumulator) - } - - _ -> accumulator - } -} - -/// Compare two bit arrays as sequences of bytes. -/// -/// ## Examples -/// -/// ```gleam -/// compare(<<1>>, <<2>>) -/// // -> Lt -/// -/// compare(<<"AB":utf8>>, <<"AA":utf8>>) -/// // -> Gt -/// -/// compare(<<1, 2:size(2)>>, with: <<1, 2:size(2)>>) -/// // -> Eq -/// ``` -/// -/// Only supported on Erlang target for now. -/// -@external(javascript, "../gleam_stdlib.mjs", "bit_array_compare") -pub fn compare(a: BitArray, with b: BitArray) -> order.Order { - case a, b { - <>, <> -> - case first_byte, second_byte { - f, s if f > s -> order.Gt - f, s if f < s -> order.Lt - _, _ -> compare(first_rest, second_rest) - } - - <<>>, <<>> -> order.Eq - // First has more items, example: "AB" > "A": - _, <<>> -> order.Gt - // Second has more items, example: "A" < "AB": - <<>>, _ -> order.Lt - // This happens when there's unusually sized elements. - // Handle these special cases via custom erlang function. - first, second -> - case bit_array_to_int_and_size(first), bit_array_to_int_and_size(second) { - #(a, _), #(b, _) if a > b -> order.Gt - #(a, _), #(b, _) if a < b -> order.Lt - #(_, size_a), #(_, size_b) if size_a > size_b -> order.Gt - #(_, size_a), #(_, size_b) if size_a < size_b -> order.Lt - _, _ -> order.Eq - } - } -} - -@external(erlang, "gleam_stdlib", "bit_array_to_int_and_size") -fn bit_array_to_int_and_size(a: BitArray) -> #(Int, Int) diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bool.gleam b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bool.gleam deleted file mode 100644 index ced8005c11d..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bool.gleam +++ /dev/null @@ -1,359 +0,0 @@ -//// A type with two possible values, `True` and `False`. Used to indicate whether -//// things are... true or false! -//// -//// Often is it clearer and offers more type safety to define a custom type -//// than to use `Bool`. For example, rather than having a `is_teacher: Bool` -//// field consider having a `role: SchoolRole` field where `SchoolRole` is a custom -//// type that can be either `Student` or `Teacher`. - -import gleam/order.{type Order} - -/// Returns the and of two bools, but it evaluates both arguments. -/// -/// It's the function equivalent of the `&&` operator. -/// This function is useful in higher order functions or pipes. -/// -/// ## Examples -/// -/// ```gleam -/// and(True, True) -/// // -> True -/// ``` -/// -/// ```gleam -/// and(False, True) -/// // -> False -/// ``` -/// -/// ```gleam -/// False |> and(True) -/// // -> False -/// ``` -/// -pub fn and(a: Bool, b: Bool) -> Bool { - a && b -} - -/// Returns the or of two bools, but it evaluates both arguments. -/// -/// It's the function equivalent of the `||` operator. -/// This function is useful in higher order functions or pipes. -/// -/// ## Examples -/// -/// ```gleam -/// or(True, True) -/// // -> True -/// ``` -/// -/// ```gleam -/// or(False, True) -/// // -> True -/// ``` -/// -/// ```gleam -/// False |> or(True) -/// // -> True -/// ``` -/// -pub fn or(a: Bool, b: Bool) -> Bool { - a || b -} - -/// Returns the opposite bool value. -/// -/// This is the same as the `!` or `not` operators in some other languages. -/// -/// ## Examples -/// -/// ```gleam -/// negate(True) -/// // -> False -/// ``` -/// -/// ```gleam -/// negate(False) -/// // -> True -/// ``` -/// -pub fn negate(bool: Bool) -> Bool { - !bool -} - -/// Returns the nor of two bools. -/// -/// ## Examples -/// -/// ```gleam -/// nor(False, False) -/// // -> True -/// ``` -/// -/// ```gleam -/// nor(False, True) -/// // -> False -/// ``` -/// -/// ```gleam -/// nor(True, False) -/// // -> False -/// ``` -/// -/// ```gleam -/// nor(True, True) -/// // -> False -/// ``` -/// -pub fn nor(a: Bool, b: Bool) -> Bool { - !{ a || b } -} - -/// Returns the nand of two bools. -/// -/// ## Examples -/// -/// ```gleam -/// nand(False, False) -/// // -> True -/// ``` -/// -/// ```gleam -/// nand(False, True) -/// // -> True -/// ``` -/// -/// ```gleam -/// nand(True, False) -/// // -> True -/// ``` -/// -/// ```gleam -/// nand(True, True) -/// // -> False -/// ``` -/// -pub fn nand(a: Bool, b: Bool) -> Bool { - !{ a && b } -} - -/// Returns the exclusive or of two bools. -/// -/// ## Examples -/// -/// ```gleam -/// exclusive_or(False, False) -/// // -> False -/// ``` -/// -/// ```gleam -/// exclusive_or(False, True) -/// // -> True -/// ``` -/// -/// ```gleam -/// exclusive_or(True, False) -/// // -> True -/// ``` -/// -/// ```gleam -/// exclusive_or(True, True) -/// // -> False -/// ``` -/// -pub fn exclusive_or(a: Bool, b: Bool) -> Bool { - a != b -} - -/// Returns the exclusive nor of two bools. -/// -/// ## Examples -/// -/// ```gleam -/// exclusive_nor(False, False) -/// // -> True -/// ``` -/// -/// ```gleam -/// exclusive_nor(False, True) -/// // -> False -/// ``` -/// -/// ```gleam -/// exclusive_nor(True, False) -/// // -> False -/// ``` -/// -/// ```gleam -/// exclusive_nor(True, True) -/// // -> True -/// ``` -/// -pub fn exclusive_nor(a: Bool, b: Bool) -> Bool { - a == b -} - -/// Compares two bools and returns the first value's `Order` to the second. -/// -/// ## Examples -/// -/// ```gleam -/// import gleam/order -/// -/// compare(True, False) -/// // -> order.Gt -/// ``` -/// -pub fn compare(a: Bool, with b: Bool) -> Order { - case a, b { - True, True -> order.Eq - True, False -> order.Gt - False, False -> order.Eq - False, True -> order.Lt - } -} - -/// Returns a numeric representation of the given bool. -/// -/// ## Examples -/// -/// ```gleam -/// to_int(True) -/// // -> 1 -/// ``` -/// -/// ```gleam -/// to_int(False) -/// // -> 0 -/// ``` -/// -pub fn to_int(bool: Bool) -> Int { - case bool { - False -> 0 - True -> 1 - } -} - -/// Returns a string representation of the given bool. -/// -/// ## Examples -/// -/// ```gleam -/// to_string(True) -/// // -> "True" -/// ``` -/// -/// ```gleam -/// to_string(False) -/// // -> "False" -/// ``` -/// -pub fn to_string(bool: Bool) -> String { - case bool { - False -> "False" - True -> "True" - } -} - -/// Run a callback function if the given bool is `False`, otherwise return a -/// default value. -/// -/// With a `use` expression this function can simulate the early-return pattern -/// found in some other programming languages. -/// -/// In a procedural language: -/// -/// ```js -/// if (predicate) return value; -/// // ... -/// ``` -/// -/// In Gleam with a `use` expression: -/// -/// ```gleam -/// use <- guard(when: predicate, return: value) -/// // ... -/// ``` -/// -/// Like everything in Gleam `use` is an expression, so it short circuits the -/// current block, not the entire function. As a result you can assign the value -/// to a variable: -/// -/// ```gleam -/// let x = { -/// use <- guard(when: predicate, return: value) -/// // ... -/// } -/// ``` -/// -/// Note that unlike in procedural languages the `return` value is evaluated -/// even when the predicate is `False`, so it is advisable not to perform -/// expensive computation nor side-effects there. -/// -/// -/// ## Examples -/// -/// ```gleam -/// let name = "" -/// use <- guard(when: name == "", return: "Welcome!") -/// "Hello, " <> name -/// // -> "Welcome!" -/// ``` -/// -/// ```gleam -/// let name = "Kamaka" -/// use <- guard(when: name == "", return: "Welcome!") -/// "Hello, " <> name -/// // -> "Hello, Kamaka" -/// ``` -/// -pub fn guard( - when requirement: Bool, - return consequence: a, - otherwise alternative: fn() -> a, -) -> a { - case requirement { - True -> consequence - False -> alternative() - } -} - -/// Runs a callback function if the given bool is `True`, otherwise runs an -/// alternative callback function. -/// -/// Useful when further computation should be delayed regardless of the given -/// bool's value. -/// -/// See [`guard`](#guard) for more info. -/// -/// ## Examples -/// -/// ```gleam -/// let name = "Kamaka" -/// let inquiry = fn() { "How may we address you?" } -/// use <- lazy_guard(when: name == "", return: inquiry) -/// "Hello, " <> name -/// // -> "Hello, Kamaka" -/// ``` -/// -/// ```gleam -/// import gleam/int -/// -/// let name = "" -/// let greeting = fn() { "Hello, " <> name } -/// use <- lazy_guard(when: name == "", otherwise: greeting) -/// let number = int.random(99) -/// let name = "User " <> int.to_string(number) -/// "Welcome, " <> name -/// // -> "Welcome, User 54" -/// ``` -/// -pub fn lazy_guard( - when requirement: Bool, - return consequence: fn() -> a, - otherwise alternative: fn() -> a, -) -> a { - case requirement { - True -> consequence() - False -> alternative() - } -} diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bytes_builder.gleam b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bytes_builder.gleam deleted file mode 100644 index fbed16b5e37..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/bytes_builder.gleam +++ /dev/null @@ -1,201 +0,0 @@ -//// `BytesBuilder` is a type used for efficiently building binary content to be -//// written to a file or a socket. Internally it is represented as tree so to -//// append or prepend to a bytes builder is a constant time operation that -//// allocates a new node in the tree without copying any of the content. When -//// writing to an output stream the tree is traversed and the content is sent -//// directly rather than copying it into a single buffer beforehand. -//// -//// If we append one bit array to another the bit arrays must be copied to a -//// new location in memory so that they can sit together. This behaviour -//// enables efficient reading of the data but copying can be expensive, -//// especially if we want to join many bit arrays together. -//// -//// BytesBuilder is different in that it can be joined together in constant -//// time using minimal memory, and then can be efficiently converted to a -//// bit array using the `to_bit_array` function. -//// -//// Byte builders are always byte aligned, so that a number of bits that is not -//// divisible by 8 will be padded with 0s. -//// -//// On Erlang this type is compatible with Erlang's iolists. - -// TODO: pad bit arrays to byte boundaries when adding to a builder. -import gleam/bit_array -import gleam/list -import gleam/string_builder.{type StringBuilder} - -pub opaque type BytesBuilder { - Bytes(BitArray) - Text(StringBuilder) - Many(List(BytesBuilder)) -} - -/// Create an empty `BytesBuilder`. Useful as the start of a pipe chaining many -/// builders together. -/// -pub fn new() -> BytesBuilder { - concat([]) -} - -/// Prepends a bit array to the start of a builder. -/// -/// Runs in constant time. -/// -pub fn prepend(to second: BytesBuilder, prefix first: BitArray) -> BytesBuilder { - append_builder(from_bit_array(first), second) -} - -/// Appends a bit array to the end of a builder. -/// -/// Runs in constant time. -/// -pub fn append(to first: BytesBuilder, suffix second: BitArray) -> BytesBuilder { - append_builder(first, from_bit_array(second)) -} - -/// Prepends a builder onto the start of another. -/// -/// Runs in constant time. -/// -pub fn prepend_builder( - to second: BytesBuilder, - prefix first: BytesBuilder, -) -> BytesBuilder { - append_builder(first, second) -} - -/// Appends a builder onto the end of another. -/// -/// Runs in constant time. -/// -@external(erlang, "gleam_stdlib", "iodata_append") -pub fn append_builder( - to first: BytesBuilder, - suffix second: BytesBuilder, -) -> BytesBuilder { - case second { - Many(builders) -> Many([first, ..builders]) - _ -> Many([first, second]) - } -} - -/// Prepends a string onto the start of a builder. -/// -/// Runs in constant time when running on Erlang. -/// Runs in linear time with the length of the string otherwise. -/// -pub fn prepend_string( - to second: BytesBuilder, - prefix first: String, -) -> BytesBuilder { - append_builder(from_string(first), second) -} - -/// Appends a string onto the end of a builder. -/// -/// Runs in constant time when running on Erlang. -/// Runs in linear time with the length of the string otherwise. -/// -pub fn append_string( - to first: BytesBuilder, - suffix second: String, -) -> BytesBuilder { - append_builder(first, from_string(second)) -} - -/// Joins a list of builders into a single builder. -/// -/// Runs in constant time. -/// -@external(erlang, "gleam_stdlib", "identity") -pub fn concat(builders: List(BytesBuilder)) -> BytesBuilder { - Many(builders) -} - -/// Joins a list of bit arrays into a single builder. -/// -/// Runs in constant time. -/// -@external(erlang, "gleam_stdlib", "identity") -pub fn concat_bit_arrays(bits: List(BitArray)) -> BytesBuilder { - bits - |> list.map(fn(b) { from_bit_array(b) }) - |> concat() -} - -/// Creates a new builder from a string. -/// -/// Runs in constant time when running on Erlang. -/// Runs in linear time otherwise. -/// -@external(erlang, "gleam_stdlib", "wrap_list") -pub fn from_string(string: String) -> BytesBuilder { - Text(string_builder.from_string(string)) -} - -/// Creates a new builder from a string builder. -/// -/// Runs in constant time when running on Erlang. -/// Runs in linear time otherwise. -/// -@external(erlang, "gleam_stdlib", "wrap_list") -pub fn from_string_builder(builder: StringBuilder) -> BytesBuilder { - Text(builder) -} - -/// Creates a new builder from a bit array. -/// -/// Runs in constant time. -/// -@external(erlang, "gleam_stdlib", "wrap_list") -pub fn from_bit_array(bits: BitArray) -> BytesBuilder { - Bytes(bits) -} - -/// Turns an builder into a bit array. -/// -/// Runs in linear time. -/// -/// When running on Erlang this function is implemented natively by the -/// virtual machine and is highly optimised. -/// -@external(erlang, "erlang", "list_to_bitstring") -pub fn to_bit_array(builder: BytesBuilder) -> BitArray { - [[builder]] - |> to_list([]) - |> list.reverse - |> bit_array.concat -} - -fn to_list( - stack: List(List(BytesBuilder)), - acc: List(BitArray), -) -> List(BitArray) { - case stack { - [] -> acc - - [[], ..remaining_stack] -> to_list(remaining_stack, acc) - - [[Bytes(bits), ..rest], ..remaining_stack] -> - to_list([rest, ..remaining_stack], [bits, ..acc]) - - [[Text(builder), ..rest], ..remaining_stack] -> { - let bits = bit_array.from_string(string_builder.to_string(builder)) - to_list([rest, ..remaining_stack], [bits, ..acc]) - } - - [[Many(builders), ..rest], ..remaining_stack] -> - to_list([builders, rest, ..remaining_stack], acc) - } -} - -/// Returns the size of the builder's content in bytes. -/// -/// Runs in linear time. -/// -@external(erlang, "erlang", "iolist_size") -pub fn byte_size(builder: BytesBuilder) -> Int { - [[builder]] - |> to_list([]) - |> list.fold(0, fn(acc, builder) { bit_array.byte_size(builder) + acc }) -} diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dict.gleam b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dict.gleam deleted file mode 100644 index 10b55445ff1..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dict.gleam +++ /dev/null @@ -1,568 +0,0 @@ -import gleam/option.{type Option} - -/// A dictionary of keys and values. -/// -/// Any type can be used for the keys and values of a dict, but all the keys -/// must be of the same type and all the values must be of the same type. -/// -/// Each key can only be present in a dict once. -/// -/// Dicts are not ordered in any way, and any unintentional ordering is not to -/// be relied upon in your code as it may change in future versions of Erlang -/// or Gleam. -/// -/// See [the Erlang map module](https://erlang.org/doc/man/maps.html) for more -/// information. -/// -pub type Dict(key, value) - -/// Determines the number of key-value pairs in the dict. -/// This function runs in constant time and does not need to iterate the dict. -/// -/// ## Examples -/// -/// ```gleam -/// new() |> size -/// // -> 0 -/// ``` -/// -/// ```gleam -/// new() |> insert("key", "value") |> size -/// // -> 1 -/// ``` -/// -@external(erlang, "maps", "size") -@external(javascript, "../gleam_stdlib.mjs", "map_size") -pub fn size(dict: Dict(k, v)) -> Int - -/// Determines whether or not the dict is empty. -/// -/// ## Examples -/// -/// ```gleam -/// new() |> is_empty -/// // -> True -/// ``` -/// -/// ```gleam -/// new() |> insert("b", 1) |> is_empty -/// // -> False -/// ``` -/// -pub fn is_empty(dict: Dict(k, v)) -> Bool { - dict == new() -} - -/// Converts the dict to a list of 2-element tuples `#(key, value)`, one for -/// each key-value pair in the dict. -/// -/// The tuples in the list have no specific order. -/// -/// ## Examples -/// -/// Calling `to_list` on an empty `dict` returns an empty list. -/// -/// ```gleam -/// new() |> to_list -/// // -> [] -/// ``` -/// -/// The ordering of elements in the resulting list is an implementation detail -/// that should not be relied upon. -/// -/// ```gleam -/// new() |> insert("b", 1) |> insert("a", 0) |> insert("c", 2) |> to_list -/// // -> [#("a", 0), #("b", 1), #("c", 2)] -/// ``` -/// -@external(erlang, "maps", "to_list") -@external(javascript, "../gleam_stdlib.mjs", "map_to_list") -pub fn to_list(dict: Dict(k, v)) -> List(#(k, v)) - -/// Converts a list of 2-element tuples `#(key, value)` to a dict. -/// -/// If two tuples have the same key the last one in the list will be the one -/// that is present in the dict. -/// -@external(erlang, "maps", "from_list") -pub fn from_list(list: List(#(k, v))) -> Dict(k, v) { - fold_list_of_pair(list, new()) -} - -fn fold_list_of_pair( - over list: List(#(k, v)), - from initial: Dict(k, v), -) -> Dict(k, v) { - case list { - [] -> initial - [x, ..rest] -> fold_list_of_pair(rest, insert(initial, x.0, x.1)) - } -} - -/// Determines whether or not a value present in the dict for a given key. -/// -/// ## Examples -/// -/// ```gleam -/// new() |> insert("a", 0) |> has_key("a") -/// // -> True -/// ``` -/// -/// ```gleam -/// new() |> insert("a", 0) |> has_key("b") -/// // -> False -/// ``` -/// -pub fn has_key(dict: Dict(k, v), key: k) -> Bool { - do_has_key(key, dict) -} - -@external(erlang, "maps", "is_key") -fn do_has_key(key: k, dict: Dict(k, v)) -> Bool { - get(dict, key) != Error(Nil) -} - -/// Creates a fresh dict that contains no values. -/// -pub fn new() -> Dict(k, v) { - do_new() -} - -@external(erlang, "maps", "new") -@external(javascript, "../gleam_stdlib.mjs", "new_map") -fn do_new() -> Dict(k, v) - -/// Fetches a value from a dict for a given key. -/// -/// The dict may not have a value for the key, so the value is wrapped in a -/// `Result`. -/// -/// ## Examples -/// -/// ```gleam -/// new() |> insert("a", 0) |> get("a") -/// // -> Ok(0) -/// ``` -/// -/// ```gleam -/// new() |> insert("a", 0) |> get("b") -/// // -> Error(Nil) -/// ``` -/// -pub fn get(from: Dict(k, v), get: k) -> Result(v, Nil) { - do_get(from, get) -} - -@external(erlang, "gleam_stdlib", "map_get") -@external(javascript, "../gleam_stdlib.mjs", "map_get") -fn do_get(dict: Dict(k, v), key: k) -> Result(v, Nil) - -/// Inserts a value into the dict with the given key. -/// -/// If the dict already has a value for the given key then the value is -/// replaced with the new value. -/// -/// ## Examples -/// -/// ```gleam -/// new() |> insert("a", 0) -/// // -> from_list([#("a", 0)]) -/// ``` -/// -/// ```gleam -/// new() |> insert("a", 0) |> insert("a", 5) -/// // -> from_list([#("a", 5)]) -/// ``` -/// -pub fn insert(into dict: Dict(k, v), for key: k, insert value: v) -> Dict(k, v) { - do_insert(key, value, dict) -} - -@external(erlang, "maps", "put") -@external(javascript, "../gleam_stdlib.mjs", "map_insert") -fn do_insert(key: k, value: v, dict: Dict(k, v)) -> Dict(k, v) - -/// Updates all values in a given dict by calling a given function on each key -/// and value. -/// -/// ## Examples -/// -/// ```gleam -/// from_list([#(3, 3), #(2, 4)]) -/// |> map_values(fn(key, value) { key * value }) -/// // -> from_list([#(3, 9), #(2, 8)]) -/// ``` -/// -pub fn map_values(in dict: Dict(k, v), with fun: fn(k, v) -> a) -> Dict(k, a) { - do_map_values(fun, dict) -} - -@external(erlang, "maps", "map") -fn do_map_values(f: fn(k, v) -> a, dict: Dict(k, v)) -> Dict(k, a) { - let f = fn(dict, k, v) { insert(dict, k, f(k, v)) } - fold(dict, from: new(), with: f) -} - -/// Gets a list of all keys in a given dict. -/// -/// Dicts are not ordered so the keys are not returned in any specific order. Do -/// not write code that relies on the order keys are returned by this function -/// as it may change in later versions of Gleam or Erlang. -/// -/// ## Examples -/// -/// ```gleam -/// from_list([#("a", 0), #("b", 1)]) |> keys -/// // -> ["a", "b"] -/// ``` -/// -pub fn keys(dict: Dict(k, v)) -> List(k) { - do_keys(dict) -} - -@external(erlang, "maps", "keys") -fn do_keys(dict: Dict(k, v)) -> List(k) { - let list_of_pairs = to_list(dict) - do_keys_acc(list_of_pairs, []) -} - -fn reverse_and_concat(remaining: List(a), accumulator: List(a)) -> List(a) { - case remaining { - [] -> accumulator - [item, ..rest] -> reverse_and_concat(rest, [item, ..accumulator]) - } -} - -fn do_keys_acc(list: List(#(k, v)), acc: List(k)) -> List(k) { - case list { - [] -> reverse_and_concat(acc, []) - [first, ..rest] -> do_keys_acc(rest, [first.0, ..acc]) - } -} - -/// Gets a list of all values in a given dict. -/// -/// Dicts are not ordered so the values are not returned in any specific order. Do -/// not write code that relies on the order values are returned by this function -/// as it may change in later versions of Gleam or Erlang. -/// -/// ## Examples -/// -/// ```gleam -/// from_list([#("a", 0), #("b", 1)]) |> values -/// // -> [0, 1] -/// ``` -/// -pub fn values(dict: Dict(k, v)) -> List(v) { - do_values(dict) -} - -@external(erlang, "maps", "values") -fn do_values(dict: Dict(k, v)) -> List(v) { - let list_of_pairs = to_list(dict) - do_values_acc(list_of_pairs, []) -} - -fn do_values_acc(list: List(#(k, v)), acc: List(v)) -> List(v) { - case list { - [] -> reverse_and_concat(acc, []) - [first, ..rest] -> do_values_acc(rest, [first.1, ..acc]) - } -} - -/// Creates a new dict from a given dict, minus any entries that a given function -/// returns `False` for. -/// -/// ## Examples -/// -/// ```gleam -/// from_list([#("a", 0), #("b", 1)]) -/// |> filter(fn(key, value) { value != 0 }) -/// // -> from_list([#("b", 1)]) -/// ``` -/// -/// ```gleam -/// from_list([#("a", 0), #("b", 1)]) -/// |> filter(fn(key, value) { True }) -/// // -> from_list([#("a", 0), #("b", 1)]) -/// ``` -/// -pub fn filter( - in dict: Dict(k, v), - keeping predicate: fn(k, v) -> Bool, -) -> Dict(k, v) { - do_filter(predicate, dict) -} - -@external(erlang, "maps", "filter") -fn do_filter(f: fn(k, v) -> Bool, dict: Dict(k, v)) -> Dict(k, v) { - let insert = fn(dict, k, v) { - case f(k, v) { - True -> insert(dict, k, v) - _ -> dict - } - } - dict - |> fold(from: new(), with: insert) -} - -/// Creates a new dict from a given dict, only including any entries for which the -/// keys are in a given list. -/// -/// ## Examples -/// -/// ```gleam -/// from_list([#("a", 0), #("b", 1)]) -/// |> take(["b"]) -/// // -> from_list([#("b", 1)]) -/// ``` -/// -/// ```gleam -/// from_list([#("a", 0), #("b", 1)]) -/// |> take(["a", "b", "c"]) -/// // -> from_list([#("a", 0), #("b", 1)]) -/// ``` -/// -pub fn take(from dict: Dict(k, v), keeping desired_keys: List(k)) -> Dict(k, v) { - do_take(desired_keys, dict) -} - -@external(erlang, "maps", "with") -fn do_take(desired_keys: List(k), dict: Dict(k, v)) -> Dict(k, v) { - insert_taken(dict, desired_keys, new()) -} - -fn insert_taken( - dict: Dict(k, v), - desired_keys: List(k), - acc: Dict(k, v), -) -> Dict(k, v) { - let insert = fn(taken, key) { - case get(dict, key) { - Ok(value) -> insert(taken, key, value) - _ -> taken - } - } - case desired_keys { - [] -> acc - [first, ..rest] -> insert_taken(dict, rest, insert(acc, first)) - } -} - -/// Creates a new dict from a pair of given dicts by combining their entries. -/// -/// If there are entries with the same keys in both dicts the entry from the -/// second dict takes precedence. -/// -/// ## Examples -/// -/// ```gleam -/// let a = from_list([#("a", 0), #("b", 1)]) -/// let b = from_list([#("b", 2), #("c", 3)]) -/// merge(a, b) -/// // -> from_list([#("a", 0), #("b", 2), #("c", 3)]) -/// ``` -/// -pub fn merge(into dict: Dict(k, v), from new_entries: Dict(k, v)) -> Dict(k, v) { - do_merge(dict, new_entries) -} - -@external(erlang, "maps", "merge") -fn do_merge(dict: Dict(k, v), new_entries: Dict(k, v)) -> Dict(k, v) { - new_entries - |> to_list - |> fold_inserts(dict) -} - -fn insert_pair(dict: Dict(k, v), pair: #(k, v)) -> Dict(k, v) { - insert(dict, pair.0, pair.1) -} - -fn fold_inserts(new_entries: List(#(k, v)), dict: Dict(k, v)) -> Dict(k, v) { - case new_entries { - [] -> dict - [first, ..rest] -> fold_inserts(rest, insert_pair(dict, first)) - } -} - -/// Creates a new dict from a given dict with all the same entries except for the -/// one with a given key, if it exists. -/// -/// ## Examples -/// -/// ```gleam -/// from_list([#("a", 0), #("b", 1)]) |> delete("a") -/// // -> from_list([#("b", 1)]) -/// ``` -/// -/// ```gleam -/// from_list([#("a", 0), #("b", 1)]) |> delete("c") -/// // -> from_list([#("a", 0), #("b", 1)]) -/// ``` -/// -pub fn delete(from dict: Dict(k, v), delete key: k) -> Dict(k, v) { - do_delete(key, dict) -} - -@external(erlang, "maps", "remove") -@external(javascript, "../gleam_stdlib.mjs", "map_remove") -fn do_delete(a: k, b: Dict(k, v)) -> Dict(k, v) - -/// Creates a new dict from a given dict with all the same entries except any with -/// keys found in a given list. -/// -/// ## Examples -/// -/// ```gleam -/// from_list([#("a", 0), #("b", 1)]) |> drop(["a"]) -/// // -> from_list([#("b", 1)]) -/// ``` -/// -/// ```gleam -/// from_list([#("a", 0), #("b", 1)]) |> drop(["c"]) -/// // -> from_list([#("a", 0), #("b", 1)]) -/// ``` -/// -/// ```gleam -/// from_list([#("a", 0), #("b", 1)]) |> drop(["a", "b", "c"]) -/// // -> from_list([]) -/// ``` -/// -pub fn drop(from dict: Dict(k, v), drop disallowed_keys: List(k)) -> Dict(k, v) { - case disallowed_keys { - [] -> dict - [first, ..rest] -> drop(delete(dict, first), rest) - } -} - -/// Creates a new dict with one entry inserted or updated using a given function. -/// -/// If there was not an entry in the dict for the given key then the function -/// gets `None` as its argument, otherwise it gets `Some(value)`. -/// -/// ## Example -/// -/// ```gleam -/// let dict = from_list([#("a", 0)]) -/// let increment = fn(x) { -/// case x { -/// Some(i) -> i + 1 -/// None -> 0 -/// } -/// } -/// -/// upsert(dict, "a", increment) -/// // -> from_list([#("a", 1)]) -/// -/// upsert(dict, "b", increment) -/// // -> from_list([#("a", 0), #("b", 0)]) -/// ``` -/// -pub fn upsert( - in dict: Dict(k, v), - update key: k, - with fun: fn(Option(v)) -> v, -) -> Dict(k, v) { - dict - |> get(key) - |> option.from_result - |> fun - |> insert(dict, key, _) -} - -fn do_fold(list: List(#(k, v)), initial: acc, fun: fn(acc, k, v) -> acc) -> acc { - case list { - [] -> initial - [#(k, v), ..rest] -> do_fold(rest, fun(initial, k, v), fun) - } -} - -/// Combines all entries into a single value by calling a given function on each -/// one. -/// -/// Dicts are not ordered so the values are not returned in any specific order. Do -/// not write code that relies on the order entries are used by this function -/// as it may change in later versions of Gleam or Erlang. -/// -/// # Examples -/// -/// ```gleam -/// let dict = from_list([#("a", 1), #("b", 3), #("c", 9)]) -/// fold(dict, 0, fn(accumulator, key, value) { accumulator + value }) -/// // -> 13 -/// ``` -/// -/// ```gleam -/// import gleam/string -/// -/// let dict = from_list([#("a", 1), #("b", 3), #("c", 9)]) -/// fold(dict, "", fn(accumulator, key, value) { -/// string.append(accumulator, key) -/// }) -/// // -> "abc" -/// ``` -/// -pub fn fold( - over dict: Dict(k, v), - from initial: acc, - with fun: fn(acc, k, v) -> acc, -) -> acc { - dict - |> to_list - |> do_fold(initial, fun) -} - -/// Calls a function for each key and value in a dict, discarding the return -/// value. -/// -/// Useful for producing a side effect for every item of a dict. -/// -/// ```gleam -/// import gleam/io -/// -/// let dict = from_list([#("a", "apple"), #("b", "banana"), #("c", "cherry")]) -/// -/// each(dict, fn(k, v) { -/// io.println(key <> " => " <> value) -/// }) -/// // -> Nil -/// // a => apple -/// // b => banana -/// // c => cherry -/// ``` -/// -/// The order of elements in the iteration is an implementation detail that -/// should not be relied upon. -/// -pub fn each(dict: Dict(k, v), fun: fn(k, v) -> a) -> Nil { - fold(dict, Nil, fn(nil, k, v) { - fun(k, v) - nil - }) -} - -/// Creates a new dict from a pair of given dicts by combining their entries. -/// -/// If there are entries with the same keys in both dicts the given function is -/// used to determine the new value to use in the resulting dict. -/// -/// ## Examples -/// -/// ```gleam -/// let a = from_list([#("a", 0), #("b", 1)]) -/// let b = from_list([#("a", 2), #("c", 3)]) -/// combine(a, b, fn(one, other) { one + other }) -/// // -> from_list([#("a", 2), #("b", 1), #("c", 3)]) -/// ``` -/// -pub fn combine( - dict: Dict(k, v), - other: Dict(k, v), - with fun: fn(v, v) -> v, -) -> Dict(k, v) { - use acc, key, value <- fold(over: dict, from: other) - case get(acc, key) { - Ok(other_value) -> insert(acc, key, fun(value, other_value)) - Error(_) -> insert(acc, key, value) - } -} diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam deleted file mode 100644 index f142034fb29..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/dynamic.gleam +++ /dev/null @@ -1,1522 +0,0 @@ -import gleam/bit_array -import gleam/dict.{type Dict} -import gleam/int -import gleam/list -import gleam/option.{type Option, Some} -import gleam/result -import gleam/string_builder - -/// `Dynamic` data is data that we don't know the type of yet. -/// We likely get data like this from interop with Erlang, or from -/// IO with the outside world. -/// -pub type Dynamic - -/// Error returned when unexpected data is encountered -/// -pub type DecodeError { - DecodeError(expected: String, found: String, path: List(String)) -} - -pub type DecodeErrors = - List(DecodeError) - -pub type Decoder(t) = - fn(Dynamic) -> Result(t, DecodeErrors) - -/// Converts any Gleam data into `Dynamic` data. -/// -@external(erlang, "gleam_stdlib", "identity") -@external(javascript, "../gleam_stdlib.mjs", "identity") -pub fn from(a: anything) -> Dynamic - -/// Decodes a `Dynamic` value from a `Dynamic` value. -/// -/// This function doesn't seem very useful at first, but it can be convenient -/// when you need to give a decoder function but you don't actually care what -/// the to-decode value is. -/// -pub fn dynamic(value: Dynamic) -> Result(Dynamic, List(DecodeError)) { - Ok(value) -} - -/// Checks to see whether a `Dynamic` value is a bit array, and returns that bit -/// array if it is. -/// -/// ## Examples -/// -/// ```gleam -/// import gleam/bit_array -/// -/// bit_array(from("Hello")) == bit_array.from_string("Hello") -/// // -> True -/// ``` -/// -/// ```gleam -/// bit_array(from(123)) -/// // -> Error([DecodeError(expected: "BitArray", found: "Int", path: [])]) -/// ``` -/// -pub fn bit_array(from data: Dynamic) -> Result(BitArray, DecodeErrors) { - decode_bit_array(data) -} - -@external(erlang, "gleam_stdlib", "decode_bit_array") -@external(javascript, "../gleam_stdlib.mjs", "decode_bit_array") -fn decode_bit_array(a: Dynamic) -> Result(BitArray, DecodeErrors) - -/// Checks to see whether a `Dynamic` value is a string, and returns that string if -/// it is. -/// -/// ## Examples -/// -/// ```gleam -/// string(from("Hello")) -/// // -> Ok("Hello") -/// ``` -/// -/// ```gleam -/// string(from(123)) -/// // -> Error([DecodeError(expected: "String", found: "Int", path: [])]) -/// ``` -/// -pub fn string(from data: Dynamic) -> Result(String, DecodeErrors) { - decode_string(data) -} - -fn map_errors( - result: Result(a, DecodeErrors), - f: fn(DecodeError) -> DecodeError, -) -> Result(a, DecodeErrors) { - result.map_error(result, list.map(_, f)) -} - -@external(javascript, "../gleam_stdlib.mjs", "decode_string") -fn decode_string(data: Dynamic) -> Result(String, DecodeErrors) { - bit_array(data) - |> map_errors(put_expected(_, "String")) - |> result.try(fn(raw) { - case bit_array.to_string(raw) { - Ok(string) -> Ok(string) - Error(Nil) -> - Error([DecodeError(expected: "String", found: "BitArray", path: [])]) - } - }) -} - -fn put_expected(error: DecodeError, expected: String) -> DecodeError { - DecodeError(..error, expected: expected) -} - -/// Return a string indicating the type of the dynamic value. -/// -/// ```gleam -/// classify(from("Hello")) -/// // -> "String" -/// ``` -/// -pub fn classify(data: Dynamic) -> String { - do_classify(data) -} - -@external(erlang, "gleam_stdlib", "classify_dynamic") -@external(javascript, "../gleam_stdlib.mjs", "classify_dynamic") -fn do_classify(a: Dynamic) -> String - -/// Checks to see whether a `Dynamic` value is an int, and returns that int if it -/// is. -/// -/// ## Examples -/// -/// ```gleam -/// int(from(123)) -/// // -> Ok(123) -/// ``` -/// -/// ```gleam -/// int(from("Hello")) -/// // -> Error([DecodeError(expected: "Int", found: "String", path: [])]) -/// ``` -/// -pub fn int(from data: Dynamic) -> Result(Int, DecodeErrors) { - decode_int(data) -} - -@external(erlang, "gleam_stdlib", "decode_int") -@external(javascript, "../gleam_stdlib.mjs", "decode_int") -fn decode_int(a: Dynamic) -> Result(Int, DecodeErrors) - -/// Checks to see whether a `Dynamic` value is a float, and returns that float if -/// it is. -/// -/// ## Examples -/// -/// ```gleam -/// float(from(2.0)) -/// // -> Ok(2.0) -/// ``` -/// -/// ```gleam -/// float(from(123)) -/// // -> Error([DecodeError(expected: "Float", found: "Int", path: [])]) -/// ``` -/// -pub fn float(from data: Dynamic) -> Result(Float, DecodeErrors) { - decode_float(data) -} - -@external(erlang, "gleam_stdlib", "decode_float") -@external(javascript, "../gleam_stdlib.mjs", "decode_float") -fn decode_float(a: Dynamic) -> Result(Float, DecodeErrors) - -/// Checks to see whether a `Dynamic` value is a bool, and returns that bool if -/// it is. -/// -/// ## Examples -/// -/// ```gleam -/// bool(from(True)) -/// // -> Ok(True) -/// ``` -/// -/// ```gleam -/// bool(from(123)) -/// // -> Error([DecodeError(expected: "Bool", found: "Int", path: [])]) -/// ``` -/// -pub fn bool(from data: Dynamic) -> Result(Bool, DecodeErrors) { - decode_bool(data) -} - -@external(erlang, "gleam_stdlib", "decode_bool") -@external(javascript, "../gleam_stdlib.mjs", "decode_bool") -fn decode_bool(a: Dynamic) -> Result(Bool, DecodeErrors) - -/// Checks to see whether a `Dynamic` value is a list, and returns that list if it -/// is. The types of the elements are not checked. -/// -/// If you wish to decode all the elements in the list use the `list` function -/// instead. -/// -/// ## Examples -/// -/// ```gleam -/// shallow_list(from(["a", "b", "c"])) -/// // -> Ok([from("a"), from("b"), from("c")]) -/// ``` -/// -/// ```gleam -/// shallow_list(1) -/// // -> Error([DecodeError(expected: "List", found: "Int", path: [])]) -/// ``` -/// -pub fn shallow_list(from value: Dynamic) -> Result(List(Dynamic), DecodeErrors) { - decode_list(value) -} - -@external(erlang, "gleam_stdlib", "decode_list") -@external(javascript, "../gleam_stdlib.mjs", "decode_list") -fn decode_list(a: Dynamic) -> Result(List(Dynamic), DecodeErrors) - -@external(erlang, "gleam_stdlib", "decode_result") -@external(javascript, "../gleam_stdlib.mjs", "decode_result") -fn decode_result(a: Dynamic) -> Result(Result(a, e), DecodeErrors) - -/// Checks to see whether a `Dynamic` value is a result of a particular type, and -/// returns that result if it is. -/// -/// The `ok` and `error` arguments are decoders for decoding the `Ok` and -/// `Error` values of the result. -/// -/// ## Examples -/// -/// ```gleam -/// from(Ok(1)) |> result(ok: int, error: string) -/// // -> Ok(Ok(1)) -/// ``` -/// -/// ```gleam -/// from(Error("boom")) |> result(ok: int, error: string) -/// // -> Ok(Error("boom")) -/// ``` -/// -/// ```gleam -/// from(123) |> result(ok: int, error: string) -/// // -> Error([DecodeError(expected: "Result", found: "Int", path: [])]) -/// ``` -/// -pub fn result( - ok decode_ok: Decoder(a), - error decode_error: Decoder(e), -) -> Decoder(Result(a, e)) { - fn(value) { - use inner_result <- result.try(decode_result(value)) - - case inner_result { - Ok(raw) -> { - use value <- result.try( - decode_ok(raw) - |> map_errors(push_path(_, "ok")), - ) - Ok(Ok(value)) - } - Error(raw) -> { - use value <- result.try( - decode_error(raw) - |> map_errors(push_path(_, "error")), - ) - Ok(Error(value)) - } - } - } -} - -/// Checks to see whether a `Dynamic` value is a list of a particular type, and -/// returns that list if it is. -/// -/// The second argument is a decoder function used to decode the elements of -/// the list. The list is only decoded if all elements in the list can be -/// successfully decoded using this function. -/// -/// If you do not wish to decode all the elements in the list use the `shallow_list` -/// function instead. -/// -/// ## Examples -/// -/// ```gleam -/// from(["a", "b", "c"]) |> list(of: string) -/// // -> Ok(["a", "b", "c"]) -/// ``` -/// -/// ```gleam -/// from([1, 2, 3]) |> list(of: string) -/// // -> Error([DecodeError(expected: "String", found: "Int", path: ["*"])]) -/// ``` -/// -/// ```gleam -/// from("ok") |> list(of: string) -/// // -> Error([DecodeError(expected: "List", found: "String", path: [])]) -/// ``` -/// -pub fn list( - of decoder_type: fn(Dynamic) -> Result(inner, DecodeErrors), -) -> Decoder(List(inner)) { - fn(dynamic) { - use list <- result.try(shallow_list(dynamic)) - list - |> list.try_map(decoder_type) - |> map_errors(push_path(_, "*")) - } -} - -/// Checks to see if a `Dynamic` value is a nullable version of a particular -/// type, and returns a corresponding `Option` if it is. -/// -/// ## Examples -/// -/// ```gleam -/// from("Hello") |> optional(string) -/// // -> Ok(Some("Hello")) -/// ``` -/// -/// ```gleam -/// from("Hello") |> optional(string) -/// // -> Ok(Some("Hello")) -/// ``` -/// -/// ```gleam -/// // `gleam/erlang/*` is available via the `gleam_erlang` package -/// import gleam/erlang/atom -/// -/// from(atom.from_string("null")) |> optional(string) -/// // -> Ok(None) -/// ``` -/// -/// ```gleam -/// // `gleam/erlang/*` is available via the `gleam_erlang` package -/// import gleam/erlang/atom -/// -/// from(atom.from_string("nil")) |> optional(string) -/// // -> Ok(None) -/// ``` -/// -/// ```gleam -/// // `gleam/erlang/*` is available via the `gleam_erlang` package -/// import gleam/erlang/atom -/// -/// from(atom.from_string("undefined")) |> optional(string) -/// // -> Ok(None) -/// ``` -/// -/// ```gleam -/// from(123) |> optional(string) -/// // -> Error([DecodeError(expected: "String", found: "Int", path: [])]) -/// ``` -/// -pub fn optional(of decode: Decoder(inner)) -> Decoder(Option(inner)) { - fn(value) { decode_optional(value, decode) } -} - -@external(erlang, "gleam_stdlib", "decode_option") -@external(javascript, "../gleam_stdlib.mjs", "decode_option") -fn decode_optional(a: Dynamic, b: Decoder(a)) -> Result(Option(a), DecodeErrors) - -/// Checks to see if a `Dynamic` value is a map with a specific field, and returns -/// the value of that field if it is. -/// -/// This will not succeed on a record. -/// -/// ## Examples -/// -/// ```gleam -/// import gleam/dict -/// dict.new() -/// |> dict.insert("Hello", "World") -/// |> from -/// |> field(named: "Hello", of: string) -/// // -> Ok("World") -/// ``` -/// -/// ```gleam -/// from(123) |> field("Hello", string) -/// // -> Error([DecodeError(expected: "Map", found: "Int", path: [])]) -/// ``` -/// -pub fn field(named name: a, of inner_type: Decoder(t)) -> Decoder(t) { - fn(value) { - let missing_field_error = - DecodeError(expected: "field", found: "nothing", path: []) - - use maybe_inner <- result.try(decode_field(value, name)) - maybe_inner - |> option.to_result([missing_field_error]) - |> result.try(inner_type) - |> map_errors(push_path(_, name)) - } -} - -/// Checks to see if a `Dynamic` value is a map with a specific field. -/// If the map does not have the specified field, returns an `Ok(None)` instead of failing; otherwise, -/// returns the decoded field wrapped in `Some(_)`. -/// -/// ## Examples -/// -/// ```gleam -/// import gleam/dict -/// dict.new() -/// |> dict.insert("Hello", "World") -/// |> from -/// |> optional_field(named: "Hello", of: string) -/// // -> Ok(Some("World")) -/// ``` -/// -/// ```gleam -/// import gleam/dict -/// dict.new() -/// |> from -/// |> optional_field(named: "Hello", of: string) -/// // -> Ok(None) -/// ``` -/// -/// ```gleam -/// from(123) -/// |> optional_field("Hello", string) -/// // -> Error([DecodeError(expected: "Map", found: "Int", path: [])]) -/// ``` -/// -pub fn optional_field( - named name: a, - of inner_type: Decoder(t), -) -> Decoder(Option(t)) { - fn(value) { - use maybe_inner <- result.try(decode_field(value, name)) - case maybe_inner { - option.None -> Ok(option.None) - option.Some(dynamic_inner) -> - inner_type(dynamic_inner) - |> result.map(Some) - |> map_errors(push_path(_, name)) - } - } -} - -@external(erlang, "gleam_stdlib", "decode_field") -@external(javascript, "../gleam_stdlib.mjs", "decode_field") -fn decode_field(a: Dynamic, b: name) -> Result(Option(Dynamic), DecodeErrors) - -/// Checks to see if a `Dynamic` value is a tuple large enough to have a certain -/// index, and returns the value of that index if it is. -/// -/// ## Examples -/// -/// ```gleam -/// from(#(1, 2)) -/// |> element(0, int) -/// // -> Ok(from(1)) -/// ``` -/// -/// ```gleam -/// from(#(1, 2)) -/// |> element(2, int) -/// // -> Error([ -/// // DecodeError( -/// // expected: "Tuple of at least 3 elements", -/// // found: "Tuple of 2 elements", -/// // path: [], -/// // ), -/// // ]) -/// ``` -/// -pub fn element(at index: Int, of inner_type: Decoder(inner)) -> Decoder(inner) { - fn(data: Dynamic) { - use tuple <- result.try(decode_tuple(data)) - let size = tuple_size(tuple) - use data <- result.try(case index >= 0 { - True -> - case index < size { - True -> tuple_get(tuple, index) - False -> at_least_decode_tuple_error(index + 1, data) - } - False -> - case int.absolute_value(index) <= size { - True -> tuple_get(tuple, size + index) - False -> at_least_decode_tuple_error(int.absolute_value(index), data) - } - }) - inner_type(data) - |> map_errors(push_path(_, index)) - } -} - -fn at_least_decode_tuple_error( - size: Int, - data: Dynamic, -) -> Result(a, DecodeErrors) { - let s = case size { - 1 -> "" - _ -> "s" - } - let error = - ["Tuple of at least ", int.to_string(size), " element", s] - |> string_builder.from_strings - |> string_builder.to_string - |> DecodeError(found: classify(data), path: []) - Error([error]) -} - -// A tuple of unknown size -type UnknownTuple - -@external(erlang, "gleam_stdlib", "decode_tuple") -@external(javascript, "../gleam_stdlib.mjs", "decode_tuple") -fn decode_tuple(a: Dynamic) -> Result(UnknownTuple, DecodeErrors) - -@external(erlang, "gleam_stdlib", "decode_tuple2") -@external(javascript, "../gleam_stdlib.mjs", "decode_tuple2") -fn decode_tuple2(a: Dynamic) -> Result(#(Dynamic, Dynamic), DecodeErrors) - -@external(erlang, "gleam_stdlib", "decode_tuple3") -@external(javascript, "../gleam_stdlib.mjs", "decode_tuple3") -fn decode_tuple3( - a: Dynamic, -) -> Result(#(Dynamic, Dynamic, Dynamic), DecodeErrors) - -@external(erlang, "gleam_stdlib", "decode_tuple4") -@external(javascript, "../gleam_stdlib.mjs", "decode_tuple4") -fn decode_tuple4( - a: Dynamic, -) -> Result(#(Dynamic, Dynamic, Dynamic, Dynamic), DecodeErrors) - -@external(erlang, "gleam_stdlib", "decode_tuple5") -@external(javascript, "../gleam_stdlib.mjs", "decode_tuple5") -fn decode_tuple5( - a: Dynamic, -) -> Result(#(Dynamic, Dynamic, Dynamic, Dynamic, Dynamic), DecodeErrors) - -@external(erlang, "gleam_stdlib", "decode_tuple6") -@external(javascript, "../gleam_stdlib.mjs", "decode_tuple6") -fn decode_tuple6( - a: Dynamic, -) -> Result( - #(Dynamic, Dynamic, Dynamic, Dynamic, Dynamic, Dynamic), - DecodeErrors, -) - -@external(erlang, "gleam_stdlib", "tuple_get") -@external(javascript, "../gleam_stdlib.mjs", "tuple_get") -fn tuple_get(a: UnknownTuple, b: Int) -> Result(Dynamic, DecodeErrors) - -@external(erlang, "gleam_stdlib", "size_of_tuple") -@external(javascript, "../gleam_stdlib.mjs", "length") -fn tuple_size(a: UnknownTuple) -> Int - -fn tuple_errors( - result: Result(a, List(DecodeError)), - name: String, -) -> List(DecodeError) { - case result { - Ok(_) -> [] - Error(errors) -> list.map(errors, push_path(_, name)) - } -} - -fn push_path(error: DecodeError, name: t) -> DecodeError { - let name = from(name) - let decoder = any([string, fn(x) { result.map(int(x), int.to_string) }]) - let name = case decoder(name) { - Ok(name) -> name - Error(_) -> - ["<", classify(name), ">"] - |> string_builder.from_strings - |> string_builder.to_string - } - DecodeError(..error, path: [name, ..error.path]) -} - -/// Checks to see if a `Dynamic` value is a 2-element tuple, list or array containing -/// specifically typed elements. -/// -/// ## Examples -/// -/// ```gleam -/// from(#(1, 2)) -/// |> tuple2(int, int) -/// // -> Ok(#(1, 2)) -/// ``` -/// -/// ```gleam -/// from(#(1, 2.0)) -/// |> tuple2(int, float) -/// // -> Ok(#(1, 2.0)) -/// ``` -/// -/// ```gleam -/// from([1, 2]) -/// |> tuple2(int, int) -/// // -> Ok(#(1, 2)) -/// ``` -/// -/// ```gleam -/// from([from(1), from(2.0)]) -/// |> tuple2(int, float) -/// // -> Ok(#(1, 2.0)) -/// ``` -/// -/// ```gleam -/// from(#(1, 2, 3)) -/// |> tuple2(int, float) -/// // -> Error([ -/// // DecodeError( -/// // expected: "Tuple of 2 elements", -/// // found: "Tuple of 3 elements", -/// // path: [], -/// // ), -/// // ]) -/// ``` -/// -/// ```gleam -/// from("") -/// |> tuple2(int, float) -/// // -> Error([ -/// // DecodeError( -/// // expected: "Tuple of 2 elements", -/// // found: "String", -/// // path: [], -/// // ), -/// // ]) -/// ``` -/// -pub fn tuple2( - first decode1: Decoder(a), - second decode2: Decoder(b), -) -> Decoder(#(a, b)) { - fn(value) { - use #(a, b) <- result.try(decode_tuple2(value)) - case decode1(a), decode2(b) { - Ok(a), Ok(b) -> Ok(#(a, b)) - a, b -> - tuple_errors(a, "0") - |> list.append(tuple_errors(b, "1")) - |> Error - } - } -} - -/// Checks to see if a `Dynamic` value is a 3-element tuple, list or array containing -/// specifically typed elements. -/// -/// ## Examples -/// -/// ```gleam -/// from(#(1, 2, 3)) -/// |> tuple3(int, int, int) -/// // -> Ok(#(1, 2, 3)) -/// ``` -/// -/// ```gleam -/// from(#(1, 2.0, "3")) -/// |> tuple3(int, float, string) -/// // -> Ok(#(1, 2.0, "3")) -/// ``` -/// -/// ```gleam -/// from([1, 2, 3]) -/// |> tuple3(int, int, int) -/// // -> Ok(#(1, 2, 3)) -/// ``` -/// -/// ```gleam -/// from([from(1), from(2.0), from("3")]) -/// |> tuple3(int, float, string) -/// // -> Ok(#(1, 2.0, "3")) -/// ``` -/// -/// ```gleam -/// from(#(1, 2)) -/// |> tuple3(int, float, string) -/// // -> Error([ -/// // DecodeError( -/// // expected: "Tuple of 3 elements", -/// // found: "Tuple of 2 elements", -/// // path: [], -/// // ), -/// // ]) -/// ``` -/// -/// ```gleam -/// from("") -/// |> tuple3(int, float, string) -/// // -> Error([ -/// // DecodeError( -/// // expected: "Tuple of 3 elements", -/// // found: "String", -/// // path: [], -/// // ), -/// // ]) -/// ``` -/// -pub fn tuple3( - first decode1: Decoder(a), - second decode2: Decoder(b), - third decode3: Decoder(c), -) -> Decoder(#(a, b, c)) { - fn(value) { - use #(a, b, c) <- result.try(decode_tuple3(value)) - case decode1(a), decode2(b), decode3(c) { - Ok(a), Ok(b), Ok(c) -> Ok(#(a, b, c)) - a, b, c -> - tuple_errors(a, "0") - |> list.append(tuple_errors(b, "1")) - |> list.append(tuple_errors(c, "2")) - |> Error - } - } -} - -/// Checks to see if a `Dynamic` value is a 4-element tuple, list or array containing -/// specifically typed elements. -/// -/// ## Examples -/// -/// ```gleam -/// from(#(1, 2, 3, 4)) -/// |> tuple4(int, int, int, int) -/// // -> Ok(#(1, 2, 3, 4)) -/// ``` -/// -/// ```gleam -/// from(#(1, 2.0, "3", 4)) -/// |> tuple4(int, float, string, int) -/// // -> Ok(#(1, 2.0, "3", 4)) -/// ``` -/// -/// ```gleam -/// from([1, 2, 3, 4]) -/// |> tuple4(int, int, int, int) -/// // -> Ok(#(1, 2, 3, 4)) -/// ``` -/// -/// ```gleam -/// from([from(1), from(2.0), from("3"), from(4)]) -/// |> tuple4(int, float, string, int) -/// // -> Ok(#(1, 2.0, "3", 4)) -/// ``` -/// -/// ```gleam -/// from(#(1, 2)) -/// |> tuple4(int, float, string, int) -/// // -> Error([ -/// // DecodeError( -/// // expected: "Tuple of 4 elements", -/// // found: "Tuple of 2 elements", -/// // path: [], -/// // ), -/// // ]) -/// ``` -/// -/// ```gleam -/// from("") -/// |> tuple4(int, float, string, int) -/// // -> Error([ -/// // DecodeError( -/// // expected: "Tuple of 4 elements", -/// // found: "String", -/// // path: [], -/// // ), -/// // ]) -/// ``` -/// -pub fn tuple4( - first decode1: Decoder(a), - second decode2: Decoder(b), - third decode3: Decoder(c), - fourth decode4: Decoder(d), -) -> Decoder(#(a, b, c, d)) { - fn(value) { - use #(a, b, c, d) <- result.try(decode_tuple4(value)) - case decode1(a), decode2(b), decode3(c), decode4(d) { - Ok(a), Ok(b), Ok(c), Ok(d) -> Ok(#(a, b, c, d)) - a, b, c, d -> - tuple_errors(a, "0") - |> list.append(tuple_errors(b, "1")) - |> list.append(tuple_errors(c, "2")) - |> list.append(tuple_errors(d, "3")) - |> Error - } - } -} - -/// Checks to see if a `Dynamic` value is a 5-element tuple, list or array containing -/// specifically typed elements. -/// -/// ## Examples -/// -/// ```gleam -/// from(#(1, 2, 3, 4, 5)) -/// |> tuple5(int, int, int, int, int) -/// // -> Ok(#(1, 2, 3, 4, 5)) -/// ``` -/// -/// ```gleam -/// from(#(1, 2.0, "3", 4, 5)) -/// |> tuple5(int, float, string, int, int) -/// // -> Ok(#(1, 2.0, "3", 4, 5)) -/// ``` -/// -/// ```gleam -/// from([1, 2, 3, 4, 5]) -/// |> tuple5(int, int, int, int, int) -/// // -> Ok(#(1, 2, 3, 4, 5)) -/// ``` -/// -/// ```gleam -/// from([from(1), from(2.0), from("3"), from(4), from(True)]) -/// |> tuple5(int, float, string, int, bool) -/// // -> Ok(#(1, 2.0, "3", 4, True)) -/// ``` -/// -/// ```gleam -/// from(#(1, 2)) -/// |> tuple5(int, float, string, int, int) -/// // -> Error([ -/// // DecodeError( -/// // expected: "Tuple of 5 elements", -/// // found: "Tuple of 2 elements", -/// // path: [], -/// // ), -/// // ]) -/// ``` -/// -/// ```gleam -/// from("") -/// |> tuple5(int, float, string, int, int) -/// // -> Error([ -/// // DecodeError( -/// // expected: "Tuple of 5 elements", -/// // found: "String", -/// // path: [], -/// // ), -/// // ]) -/// ``` -/// -pub fn tuple5( - first decode1: Decoder(a), - second decode2: Decoder(b), - third decode3: Decoder(c), - fourth decode4: Decoder(d), - fifth decode5: Decoder(e), -) -> Decoder(#(a, b, c, d, e)) { - fn(value) { - use #(a, b, c, d, e) <- result.try(decode_tuple5(value)) - case decode1(a), decode2(b), decode3(c), decode4(d), decode5(e) { - Ok(a), Ok(b), Ok(c), Ok(d), Ok(e) -> Ok(#(a, b, c, d, e)) - a, b, c, d, e -> - tuple_errors(a, "0") - |> list.append(tuple_errors(b, "1")) - |> list.append(tuple_errors(c, "2")) - |> list.append(tuple_errors(d, "3")) - |> list.append(tuple_errors(e, "4")) - |> Error - } - } -} - -/// Checks to see if a `Dynamic` value is a 6-element tuple, list or array containing -/// specifically typed elements. -/// -/// ## Examples -/// -/// ```gleam -/// from(#(1, 2, 3, 4, 5, 6)) -/// |> tuple6(int, int, int, int, int, int) -/// // -> Ok(#(1, 2, 3, 4, 5, 6)) -/// ``` -/// -/// ```gleam -/// from(#(1, 2.0, "3", 4, 5, 6)) -/// |> tuple6(int, float, string, int, int, int) -/// // -> Ok(#(1, 2.0, "3", 4, 5, 6)) -/// ``` -/// -/// ```gleam -/// from([1, 2, 3, 4, 5, 6]) -/// |> tuple6(int, int, int, int, int, int) -/// // -> Ok(#(1, 2, 3, 4, 5, 6)) -/// ``` -/// -/// ```gleam -/// from([from(1), from(2.0), from("3"), from(4), from(True), from(False)]) -/// |> tuple6(int, float, string, int, bool, bool) -/// // -> Ok(#(1, 2.0, "3", 4, True, False)) -/// ``` -/// -/// ```gleam -/// from(#(1, 2)) -/// |> tuple6(int, float, string, int, int, int) -/// // -> Error([ -/// // DecodeError( -/// // expected: "Tuple of 6 elements", -/// // found: "Tuple of 2 elements", -/// // path: [], -/// // ), -/// // ]) -/// ``` -/// -/// ```gleam -/// from("") -/// |> tuple6(int, float, string, int, int, int) -/// // -> Error([ -/// // DecodeError( -/// // expected: "Tuple of 6 elements", -/// // found: "String", -/// // path: [], -/// // ), -/// // ]) -/// ``` -/// -pub fn tuple6( - first decode1: Decoder(a), - second decode2: Decoder(b), - third decode3: Decoder(c), - fourth decode4: Decoder(d), - fifth decode5: Decoder(e), - sixth decode6: Decoder(f), -) -> Decoder(#(a, b, c, d, e, f)) { - fn(value) { - use #(a, b, c, d, e, f) <- result.try(decode_tuple6(value)) - case - decode1(a), - decode2(b), - decode3(c), - decode4(d), - decode5(e), - decode6(f) - { - Ok(a), Ok(b), Ok(c), Ok(d), Ok(e), Ok(f) -> Ok(#(a, b, c, d, e, f)) - a, b, c, d, e, f -> - tuple_errors(a, "0") - |> list.append(tuple_errors(b, "1")) - |> list.append(tuple_errors(c, "2")) - |> list.append(tuple_errors(d, "3")) - |> list.append(tuple_errors(e, "4")) - |> list.append(tuple_errors(f, "5")) - |> Error - } - } -} - -/// Checks to see if a `Dynamic` value is a dict. -/// -/// ## Examples -/// -/// ```gleam -/// import gleam/dict -/// dict.new() |> from |> dict(string, int) -/// // -> Ok(dict.new()) -/// ``` -/// -/// ```gleam -/// from(1) |> dict(string, int) -/// // -> Error(DecodeError(expected: "Map", found: "Int", path: [])) -/// ``` -/// -/// ```gleam -/// from("") |> dict(string, int) -/// // -> Error(DecodeError(expected: "Map", found: "String", path: [])) -/// ``` -/// -pub fn dict( - of key_type: Decoder(k), - to value_type: Decoder(v), -) -> Decoder(Dict(k, v)) { - fn(value) { - use map <- result.try(decode_map(value)) - use pairs <- result.try( - map - |> dict.to_list - |> list.try_map(fn(pair) { - let #(k, v) = pair - use k <- result.try( - key_type(k) - |> map_errors(push_path(_, "keys")), - ) - use v <- result.try( - value_type(v) - |> map_errors(push_path(_, "values")), - ) - Ok(#(k, v)) - }), - ) - Ok(dict.from_list(pairs)) - } -} - -@external(erlang, "gleam_stdlib", "decode_map") -@external(javascript, "../gleam_stdlib.mjs", "decode_map") -fn decode_map(a: Dynamic) -> Result(Dict(Dynamic, Dynamic), DecodeErrors) - -/// Joins multiple decoders into one. When run they will each be tried in turn -/// until one succeeds, or they all fail. -/// -/// ## Examples -/// -/// ```gleam -/// import gleam/result -/// -/// let bool_or_string = any(of: [ -/// string, -/// fn(x) { result.map(bool(x), fn(_) { "a bool" }) } -/// ]) -/// -/// bool_or_string(from("ok")) -/// // -> Ok("ok") -/// -/// bool_or_string(from(True)) -/// // -> Ok("a bool") -/// -/// bool_or_string(from(1)) -/// // -> Error(DecodeError(expected: "another type", found: "Int", path: [])) -/// ``` -/// -pub fn any(of decoders: List(Decoder(a))) -> Decoder(a) { - fn(data) { - case decoders { - [] -> - Error([ - DecodeError(found: classify(data), expected: "another type", path: []), - ]) - - [decoder, ..decoders] -> - case decoder(data) { - Ok(decoded) -> Ok(decoded) - Error(_) -> any(decoders)(data) - } - } - } -} - -/// Decode 1 value from a `Dynamic` value. -/// -/// ## Examples -/// -/// ```gleam -/// from(#(1, 2.0, "3")) |> decode1(MyRecord, element(0, int)) -/// // -> Ok(MyRecord(1)) -/// ``` -/// -/// ```gleam -/// from(#("", "", "")) |> decode1(MyRecord, element(0, int)) -/// // -> Error([ -/// // DecodeError(expected: "Int", found: "String", path: ["0"]), -/// // ]) -/// ``` -/// -pub fn decode1(constructor: fn(t1) -> t, t1: Decoder(t1)) -> Decoder(t) { - fn(value) { - case t1(value) { - Ok(a) -> Ok(constructor(a)) - a -> Error(all_errors(a)) - } - } -} - -/// Decode 2 values from a `Dynamic` value. -/// -/// ## Examples -/// -/// ```gleam -/// from(#(1, 2.0, "3")) -/// |> decode2(MyRecord, element(0, int), element(1, float)) -/// // -> Ok(MyRecord(1, 2.0)) -/// ``` -/// -/// ```gleam -/// from(#("", "", "")) -/// |> decode2(MyRecord, element(0, int), element(1, float)) -/// // -> Error([ -/// // DecodeError(expected: "Int", found: "String", path: ["0"]), -/// // DecodeError(expected: "Float", found: "String", path: ["1"]), -/// // ]) -/// ``` -/// -pub fn decode2( - constructor: fn(t1, t2) -> t, - t1: Decoder(t1), - t2: Decoder(t2), -) -> Decoder(t) { - fn(value) { - case t1(value), t2(value) { - Ok(a), Ok(b) -> Ok(constructor(a, b)) - a, b -> Error(list.flatten([all_errors(a), all_errors(b)])) - } - } -} - -/// Decode 3 values from a `Dynamic` value. -/// -/// ## Examples -/// -/// ```gleam -/// from(#(1, 2.0, "3")) -/// |> decode3(MyRecord, element(0, int), element(1, float), element(2, string)) -/// // -> Ok(MyRecord(1, 2.0, "3")) -/// ``` -/// -/// ```gleam -/// from(#("", "", "")) -/// |> decode3(MyRecord, element(0, int), element(1, float), element(2, string)) -/// // -> Error([ -/// // DecodeError(expected: "Int", found: "String", path: ["0"]), -/// // DecodeError(expected: "Float", found: "String", path: ["1"]), -/// // ]) -/// ``` -/// -pub fn decode3( - constructor: fn(t1, t2, t3) -> t, - t1: Decoder(t1), - t2: Decoder(t2), - t3: Decoder(t3), -) -> Decoder(t) { - fn(value) { - case t1(value), t2(value), t3(value) { - Ok(a), Ok(b), Ok(c) -> Ok(constructor(a, b, c)) - a, b, c -> - Error(list.flatten([all_errors(a), all_errors(b), all_errors(c)])) - } - } -} - -/// Decode 4 values from a `Dynamic` value. -/// -/// ## Examples -/// -/// ```gleam -/// from(#(1, 2.1, "3", "4")) -/// |> decode4( -/// MyRecord, -/// element(0, int), -/// element(1, float), -/// element(2, string), -/// element(3, string), -/// ) -/// // -> Ok(MyRecord(1, 2.1, "3", "4")) -/// ``` -/// -/// ```gleam -/// from(#("", "", "", "")) -/// |> decode4( -/// MyRecord, -/// element(0, int), -/// element(1, float), -/// element(2, string), -/// element(3, string), -/// ) -/// // -> Error([ -/// // DecodeError(expected: "Int", found: "String", path: ["0"]), -/// // DecodeError(expected: "Float", found: "String", path: ["1"]), -/// // ]) -/// ``` -/// -pub fn decode4( - constructor: fn(t1, t2, t3, t4) -> t, - t1: Decoder(t1), - t2: Decoder(t2), - t3: Decoder(t3), - t4: Decoder(t4), -) -> Decoder(t) { - fn(x: Dynamic) { - case t1(x), t2(x), t3(x), t4(x) { - Ok(a), Ok(b), Ok(c), Ok(d) -> Ok(constructor(a, b, c, d)) - a, b, c, d -> - Error( - list.flatten([ - all_errors(a), - all_errors(b), - all_errors(c), - all_errors(d), - ]), - ) - } - } -} - -/// Decode 5 values from a `Dynamic` value. -/// -/// ## Examples -/// -/// ```gleam -/// from(#(1, 2.1, "3", "4", "5")) -/// |> decode5( -/// MyRecord, -/// element(0, int), -/// element(1, float), -/// element(2, string), -/// element(3, string), -/// element(4, string), -/// ) -/// // -> Ok(MyRecord(1, 2.1, "3", "4", "5")) -/// ``` -/// -/// ```gleam -/// from(#("", "", "", "", "")) -/// |> decode5( -/// MyRecord, -/// element(0, int), -/// element(1, float), -/// element(2, string), -/// element(3, string), -/// element(4, string), -/// ) -/// // -> Error([ -/// // DecodeError(expected: "Int", found: "String", path: ["0"]), -/// // DecodeError(expected: "Float", found: "String", path: ["1"]), -/// // ]) -/// ``` -/// -pub fn decode5( - constructor: fn(t1, t2, t3, t4, t5) -> t, - t1: Decoder(t1), - t2: Decoder(t2), - t3: Decoder(t3), - t4: Decoder(t4), - t5: Decoder(t5), -) -> Decoder(t) { - fn(x: Dynamic) { - case t1(x), t2(x), t3(x), t4(x), t5(x) { - Ok(a), Ok(b), Ok(c), Ok(d), Ok(e) -> Ok(constructor(a, b, c, d, e)) - a, b, c, d, e -> - Error( - list.flatten([ - all_errors(a), - all_errors(b), - all_errors(c), - all_errors(d), - all_errors(e), - ]), - ) - } - } -} - -/// Decode 6 values from a `Dynamic` value. -/// -/// ## Examples -/// -/// ```gleam -/// from(#(1, 2.1, "3", "4", "5", "6")) -/// |> decode6( -/// MyRecord, -/// element(0, int), -/// element(1, float), -/// element(2, string), -/// element(3, string), -/// element(4, string), -/// element(5, string), -/// ) -/// // -> Ok(MyRecord(1, 2.1, "3", "4", "5", "6")) -/// ``` -/// -/// ```gleam -/// from(#("", "", "", "", "", "")) -/// |> decode6( -/// MyRecord, -/// element(0, int), -/// element(1, float), -/// element(2, string), -/// element(3, string), -/// element(4, string), -/// element(5, string), -/// ) -/// // -> Error([ -/// // DecodeError(expected: "Int", found: "String", path: ["0"]), -/// // DecodeError(expected: "Float", found: "String", path: ["1"]), -/// // ]) -/// ``` -/// -pub fn decode6( - constructor: fn(t1, t2, t3, t4, t5, t6) -> t, - t1: Decoder(t1), - t2: Decoder(t2), - t3: Decoder(t3), - t4: Decoder(t4), - t5: Decoder(t5), - t6: Decoder(t6), -) -> Decoder(t) { - fn(x: Dynamic) { - case t1(x), t2(x), t3(x), t4(x), t5(x), t6(x) { - Ok(a), Ok(b), Ok(c), Ok(d), Ok(e), Ok(f) -> - Ok(constructor(a, b, c, d, e, f)) - a, b, c, d, e, f -> - Error( - list.flatten([ - all_errors(a), - all_errors(b), - all_errors(c), - all_errors(d), - all_errors(e), - all_errors(f), - ]), - ) - } - } -} - -/// Decode 7 values from a `Dynamic` value. -/// -/// ## Examples -/// -/// ```gleam -/// from(#(1, 2.1, "3", "4", "5", "6")) -/// |> decode7( -/// MyRecord, -/// element(0, int), -/// element(1, float), -/// element(2, string), -/// element(3, string), -/// element(4, string), -/// element(5, string), -/// element(6, string), -/// ) -/// // -> Ok(MyRecord(1, 2.1, "3", "4", "5", "6", "7")) -/// ``` -/// -/// ```gleam -/// from(#("", "", "", "", "", "", "")) -/// |> decode7( -/// MyRecord, -/// element(0, int), -/// element(1, float), -/// element(2, string), -/// element(3, string), -/// element(4, string), -/// element(5, string), -/// element(6, string), -/// ) -/// // -> Error([ -/// // DecodeError(expected: "Int", found: "String", path: ["0"]), -/// // DecodeError(expected: "Float", found: "String", path: ["1"]), -/// // ]) -/// ``` -/// -pub fn decode7( - constructor: fn(t1, t2, t3, t4, t5, t6, t7) -> t, - t1: Decoder(t1), - t2: Decoder(t2), - t3: Decoder(t3), - t4: Decoder(t4), - t5: Decoder(t5), - t6: Decoder(t6), - t7: Decoder(t7), -) -> Decoder(t) { - fn(x: Dynamic) { - case t1(x), t2(x), t3(x), t4(x), t5(x), t6(x), t7(x) { - Ok(a), Ok(b), Ok(c), Ok(d), Ok(e), Ok(f), Ok(g) -> - Ok(constructor(a, b, c, d, e, f, g)) - a, b, c, d, e, f, g -> - Error( - list.flatten([ - all_errors(a), - all_errors(b), - all_errors(c), - all_errors(d), - all_errors(e), - all_errors(f), - all_errors(g), - ]), - ) - } - } -} - -/// Decode 8 values from a `Dynamic` value. -/// -/// ## Examples -/// -/// ```gleam -/// from(#(1, 2.1, "3", "4", "5", "6", "7", "8")) -/// |> decode8( -/// MyRecord, -/// element(0, int), -/// element(1, float), -/// element(2, string), -/// element(3, string), -/// element(4, string), -/// element(5, string), -/// element(6, string), -/// element(7, string), -/// ) -/// // -> Ok(MyRecord(1, 2.1, "3", "4", "5", "6", "7", "8")) -/// ``` -/// -/// ```gleam -/// from(#("", "", "", "", "", "", "", "")) -/// |> decode8( -/// MyRecord, -/// element(0, int), -/// element(1, float), -/// element(2, string), -/// element(3, string), -/// element(4, string), -/// element(5, string), -/// element(6, string), -/// element(7, string), -/// ) -/// // -> Error([ -/// // DecodeError(expected: "Int", found: "String", path: ["0"]), -/// // DecodeError(expected: "Float", found: "String", path: ["1"]), -/// // ]) -/// ``` -/// -pub fn decode8( - constructor: fn(t1, t2, t3, t4, t5, t6, t7, t8) -> t, - t1: Decoder(t1), - t2: Decoder(t2), - t3: Decoder(t3), - t4: Decoder(t4), - t5: Decoder(t5), - t6: Decoder(t6), - t7: Decoder(t7), - t8: Decoder(t8), -) -> Decoder(t) { - fn(x: Dynamic) { - case t1(x), t2(x), t3(x), t4(x), t5(x), t6(x), t7(x), t8(x) { - Ok(a), Ok(b), Ok(c), Ok(d), Ok(e), Ok(f), Ok(g), Ok(h) -> - Ok(constructor(a, b, c, d, e, f, g, h)) - a, b, c, d, e, f, g, h -> - Error( - list.flatten([ - all_errors(a), - all_errors(b), - all_errors(c), - all_errors(d), - all_errors(e), - all_errors(f), - all_errors(g), - all_errors(h), - ]), - ) - } - } -} - -/// Decode 9 values from a `Dynamic` value. -/// -/// ## Examples -/// -/// ```gleam -/// from(#(1, 2.1, "3", "4", "5", "6", "7", "8", "9")) -/// |> decode9( -/// MyRecord, -/// element(0, int), -/// element(1, float), -/// element(2, string), -/// element(3, string), -/// element(4, string), -/// element(5, string), -/// element(6, string), -/// element(7, string), -/// element(8, string), -/// ) -/// // -> Ok(MyRecord(1, 2.1, "3", "4", "5", "6", "7", "8", "9")) -/// ``` -/// -/// ```gleam -/// from(#("", "", "", "", "", "", "", "", "")) -/// |> decode9( -/// MyRecord, -/// element(0, int), -/// element(1, float), -/// element(2, string), -/// element(3, string), -/// element(4, string), -/// element(5, string), -/// element(6, string), -/// element(7, string), -/// element(8, string), -/// ) -/// // -> Error([ -/// // DecodeError(expected: "Int", found: "String", path: ["0"]), -/// // DecodeError(expected: "Float", found: "String", path: ["1"]), -/// // ]) -/// ``` -/// -pub fn decode9( - constructor: fn(t1, t2, t3, t4, t5, t6, t7, t8, t9) -> t, - t1: Decoder(t1), - t2: Decoder(t2), - t3: Decoder(t3), - t4: Decoder(t4), - t5: Decoder(t5), - t6: Decoder(t6), - t7: Decoder(t7), - t8: Decoder(t8), - t9: Decoder(t9), -) -> Decoder(t) { - fn(x: Dynamic) { - case t1(x), t2(x), t3(x), t4(x), t5(x), t6(x), t7(x), t8(x), t9(x) { - Ok(a), Ok(b), Ok(c), Ok(d), Ok(e), Ok(f), Ok(g), Ok(h), Ok(i) -> - Ok(constructor(a, b, c, d, e, f, g, h, i)) - a, b, c, d, e, f, g, h, i -> - Error( - list.flatten([ - all_errors(a), - all_errors(b), - all_errors(c), - all_errors(d), - all_errors(e), - all_errors(f), - all_errors(g), - all_errors(h), - all_errors(i), - ]), - ) - } - } -} - -fn all_errors(result: Result(a, List(DecodeError))) -> List(DecodeError) { - case result { - Ok(_) -> [] - Error(errors) -> errors - } -} diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/float.gleam b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/float.gleam deleted file mode 100644 index 7030caa345d..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/float.gleam +++ /dev/null @@ -1,599 +0,0 @@ -//// Functions for working with floats. -//// -//// ## Division by zero -//// -//// Gleam runs on the Erlang virtual machine, which does not follow the IEEE -//// 754 standard for floating point arithmetic and does not have an `Infinity` -//// value. In Erlang division by zero results in a crash, however Gleam does -//// not have partial functions and operators in core so instead division by zero -//// returns zero, a behaviour taken from Pony, Coq, and Lean. -//// -//// This may seem unexpected at first, but it is no less mathematically valid -//// than crashing or returning a special value. Division by zero is undefined -//// in mathematics. - -import gleam/order.{type Order} - -/// Attempts to parse a string as a `Float`, returning `Error(Nil)` if it was -/// not possible. -/// -/// ## Examples -/// -/// ```gleam -/// parse("2.3") -/// // -> Ok(2.3) -/// ``` -/// -/// ```gleam -/// parse("ABC") -/// // -> Error(Nil) -/// ``` -/// -pub fn parse(string: String) -> Result(Float, Nil) { - do_parse(string) -} - -@external(erlang, "gleam_stdlib", "parse_float") -@external(javascript, "../gleam_stdlib.mjs", "parse_float") -fn do_parse(a: String) -> Result(Float, Nil) - -/// Returns the string representation of the provided `Float`. -/// -/// ## Examples -/// -/// ```gleam -/// to_string(2.3) -/// // -> "2.3" -/// ``` -/// -pub fn to_string(x: Float) -> String { - do_to_string(x) -} - -@external(erlang, "gleam_stdlib", "float_to_string") -@external(javascript, "../gleam_stdlib.mjs", "float_to_string") -fn do_to_string(a: Float) -> String - -/// Restricts a `Float` between a lower and upper bound. -/// -/// ## Examples -/// -/// ```gleam -/// clamp(1.2, min: 1.4, max: 1.6) -/// // -> 1.4 -/// ``` -/// -pub fn clamp(x: Float, min min_bound: Float, max max_bound: Float) -> Float { - x - |> min(max_bound) - |> max(min_bound) -} - -/// Compares two `Float`s, returning an `Order`: -/// `Lt` for lower than, `Eq` for equals, or `Gt` for greater than. -/// -/// ## Examples -/// -/// ```gleam -/// compare(2.0, 2.3) -/// // -> Lt -/// ``` -/// -/// To handle -/// [Floating Point Imprecision](https://en.wikipedia.org/wiki/Floating-point_arithmetic#Accuracy_problems) -/// you may use [`loosely_compare`](#loosely_compare) instead. -/// -pub fn compare(a: Float, with b: Float) -> Order { - case a == b { - True -> order.Eq - False -> - case a <. b { - True -> order.Lt - False -> order.Gt - } - } -} - -/// Compares two `Float`s within a tolerance, returning an `Order`: -/// `Lt` for lower than, `Eq` for equals, or `Gt` for greater than. -/// -/// This function allows Float comparison while handling -/// [Floating Point Imprecision](https://en.wikipedia.org/wiki/Floating-point_arithmetic#Accuracy_problems). -/// -/// Notice: For `Float`s the tolerance won't be exact: -/// `5.3 - 5.0` is not exactly `0.3`. -/// -/// ## Examples -/// -/// ```gleam -/// loosely_compare(5.0, with: 5.3, tolerating: 0.5) -/// // -> Eq -/// ``` -/// -/// If you want to check only for equality you may use -/// [`loosely_equals`](#loosely_equals) instead. -/// -pub fn loosely_compare( - a: Float, - with b: Float, - tolerating tolerance: Float, -) -> Order { - let difference = absolute_value(a -. b) - case difference <=. tolerance { - True -> order.Eq - False -> compare(a, b) - } -} - -/// Checks for equality of two `Float`s within a tolerance, -/// returning an `Bool`. -/// -/// This function allows Float comparison while handling -/// [Floating Point Imprecision](https://en.wikipedia.org/wiki/Floating-point_arithmetic#Accuracy_problems). -/// -/// Notice: For `Float`s the tolerance won't be exact: -/// `5.3 - 5.0` is not exactly `0.3`. -/// -/// ## Examples -/// -/// ```gleam -/// loosely_equals(5.0, with: 5.3, tolerating: 0.5) -/// // -> True -/// ``` -/// -/// ```gleam -/// loosely_equals(5.0, with: 5.1, tolerating: 0.1) -/// // -> False -/// ``` -/// -pub fn loosely_equals( - a: Float, - with b: Float, - tolerating tolerance: Float, -) -> Bool { - let difference = absolute_value(a -. b) - difference <=. tolerance -} - -/// Compares two `Float`s, returning the smaller of the two. -/// -/// ## Examples -/// -/// ```gleam -/// min(2.0, 2.3) -/// // -> 2.0 -/// ``` -/// -pub fn min(a: Float, b: Float) -> Float { - case a <. b { - True -> a - False -> b - } -} - -/// Compares two `Float`s, returning the larger of the two. -/// -/// ## Examples -/// -/// ```gleam -/// max(2.0, 2.3) -/// // -> 2.3 -/// ``` -/// -pub fn max(a: Float, b: Float) -> Float { - case a >. b { - True -> a - False -> b - } -} - -/// Rounds the value to the next highest whole number as a `Float`. -/// -/// ## Examples -/// -/// ```gleam -/// ceiling(2.3) -/// // -> 3.0 -/// ``` -/// -pub fn ceiling(x: Float) -> Float { - do_ceiling(x) -} - -@external(erlang, "math", "ceil") -@external(javascript, "../gleam_stdlib.mjs", "ceiling") -fn do_ceiling(a: Float) -> Float - -/// Rounds the value to the next lowest whole number as a `Float`. -/// -/// ## Examples -/// -/// ```gleam -/// floor(2.3) -/// // -> 2.0 -/// ``` -/// -pub fn floor(x: Float) -> Float { - do_floor(x) -} - -@external(erlang, "math", "floor") -@external(javascript, "../gleam_stdlib.mjs", "floor") -fn do_floor(a: Float) -> Float - -/// Rounds the value to the nearest whole number as an `Int`. -/// -/// ## Examples -/// -/// ```gleam -/// round(2.3) -/// // -> 2 -/// ``` -/// -/// ```gleam -/// round(2.5) -/// // -> 3 -/// ``` -/// -pub fn round(x: Float) -> Int { - do_round(x) -} - -@external(erlang, "erlang", "round") -fn do_round(x: Float) -> Int { - case x >=. 0.0 { - True -> js_round(x) - _ -> 0 - js_round(negate(x)) - } -} - -@external(javascript, "../gleam_stdlib.mjs", "round") -fn js_round(a: Float) -> Int - -/// Returns the value as an `Int`, truncating all decimal digits. -/// -/// ## Examples -/// -/// ```gleam -/// truncate(2.4343434847383438) -/// // -> 2 -/// ``` -/// -pub fn truncate(x: Float) -> Int { - do_truncate(x) -} - -@external(erlang, "erlang", "trunc") -@external(javascript, "../gleam_stdlib.mjs", "truncate") -fn do_truncate(a: Float) -> Int - -/// Converts the value to a given precision as a `Float`. -/// The precision is the number of allowed decimal places. -/// Negative precisions are allowed and force rounding -/// to the nearest tenth, hundredth, thousandth etc. -/// -/// ## Examples -/// -/// ```gleam -/// to_precision(2.43434348473, precision: 2) -/// // -> 2.43 -/// ``` -/// -/// ```gleam -/// to_precision(547890.453444, precision: -3) -/// // -> 548000.0 -/// ``` -/// -pub fn to_precision(x: Float, precision: Int) -> Float { - let factor = do_power(10.0, do_to_float(-precision)) - do_to_float(round(x /. factor)) *. factor -} - -@external(erlang, "erlang", "float") -@external(javascript, "../gleam_stdlib.mjs", "identity") -fn do_to_float(a: Int) -> Float - -/// Returns the absolute value of the input as a `Float`. -/// -/// ## Examples -/// -/// ```gleam -/// absolute_value(-12.5) -/// // -> 12.5 -/// ``` -/// -/// ```gleam -/// absolute_value(10.2) -/// // -> 10.2 -/// ``` -/// -pub fn absolute_value(x: Float) -> Float { - case x >=. 0.0 { - True -> x - _ -> 0.0 -. x - } -} - -/// Returns the results of the base being raised to the power of the -/// exponent, as a `Float`. -/// -/// ## Examples -/// -/// ```gleam -/// power(2.0, -1.0) -/// // -> Ok(0.5) -/// ``` -/// -/// ```gleam -/// power(2.0, 2.0) -/// // -> Ok(4.0) -/// ``` -/// -/// ```gleam -/// power(8.0, 1.5) -/// // -> Ok(22.627416997969522) -/// ``` -/// -/// ```gleam -/// 4.0 |> power(of: 2.0) -/// // -> Ok(16.0) -/// ``` -/// -/// ```gleam -/// power(-1.0, 0.5) -/// // -> Error(Nil) -/// ``` -/// -pub fn power(base: Float, of exponent: Float) -> Result(Float, Nil) { - let fractional: Bool = ceiling(exponent) -. exponent >. 0.0 - // In the following check: - // 1. If the base is negative and the exponent is fractional then - // return an error as it will otherwise be an imaginary number - // 2. If the base is 0 and the exponent is negative then the expression - // is equivalent to the exponent divided by 0 and an error should be - // returned - case base <. 0.0 && fractional || base == 0.0 && exponent <. 0.0 { - True -> Error(Nil) - False -> Ok(do_power(base, exponent)) - } -} - -@external(erlang, "math", "pow") -@external(javascript, "../gleam_stdlib.mjs", "power") -fn do_power(a: Float, b: Float) -> Float - -/// Returns the square root of the input as a `Float`. -/// -/// ## Examples -/// -/// ```gleam -/// square_root(4.0) -/// // -> Ok(2.0) -/// ``` -/// -/// ```gleam -/// square_root(-16.0) -/// // -> Error(Nil) -/// ``` -/// -pub fn square_root(x: Float) -> Result(Float, Nil) { - power(x, 0.5) -} - -/// Returns the negative of the value provided. -/// -/// ## Examples -/// -/// ```gleam -/// negate(1.0) -/// // -> -1.0 -/// ``` -/// -pub fn negate(x: Float) -> Float { - -1.0 *. x -} - -/// Sums a list of `Float`s. -/// -/// ## Example -/// -/// ```gleam -/// sum([1.0, 2.2, 3.3]) -/// // -> 6.5 -/// ``` -/// -pub fn sum(numbers: List(Float)) -> Float { - numbers - |> do_sum(0.0) -} - -fn do_sum(numbers: List(Float), initial: Float) -> Float { - case numbers { - [] -> initial - [x, ..rest] -> do_sum(rest, x +. initial) - } -} - -/// Multiplies a list of `Float`s and returns the product. -/// -/// ## Example -/// -/// ```gleam -/// product([2.5, 3.2, 4.2]) -/// // -> 33.6 -/// ``` -/// -pub fn product(numbers: List(Float)) -> Float { - case numbers { - [] -> 1.0 - _ -> do_product(numbers, 1.0) - } -} - -fn do_product(numbers: List(Float), initial: Float) -> Float { - case numbers { - [] -> initial - [x, ..rest] -> do_product(rest, x *. initial) - } -} - -/// Generates a random float between the given zero (inclusive) and one -/// (exclusive). -/// -/// On Erlang this updates the random state in the process dictionary. -/// See: -/// -/// ## Examples -/// -/// ```gleam -/// random() -/// // -> 0.646355926896028 -/// ``` -/// -@external(erlang, "rand", "uniform") -@external(javascript, "../gleam_stdlib.mjs", "random_uniform") -pub fn random() -> Float - -/// Computes the modulo of an float division of inputs as a `Result`. -/// -/// Returns division of the inputs as a `Result`: If the given divisor equals -/// `0`, this function returns an `Error`. -/// -/// ## Examples -/// -/// ```gleam -/// modulo(13.3, by: 3.3) -/// // -> Ok(0.1) -/// ``` -/// -/// ```gleam -/// modulo(-13.3, by: 3.3) -/// // -> Ok(3.2) -/// ``` -/// -/// ```gleam -/// modulo(13.3, by: -3.3) -/// // -> Ok(-3.2) -/// ``` -/// -/// ```gleam -/// modulo(-13.3, by: -3.3) -/// // -> Ok(-0.1) -/// ``` -/// -pub fn modulo(dividend: Float, by divisor: Float) -> Result(Float, Nil) { - case divisor { - 0.0 -> Error(Nil) - _ -> Ok(dividend -. floor(dividend /. divisor) *. divisor) - } -} - -/// Returns division of the inputs as a `Result`. -/// -/// ## Examples -/// -/// ```gleam -/// divide(0.0, 1.0) -/// // -> Ok(0.0) -/// ``` -/// -/// ```gleam -/// divide(1.0, 0.0) -/// // -> Error(Nil) -/// ``` -/// -pub fn divide(a: Float, by b: Float) -> Result(Float, Nil) { - case b { - 0.0 -> Error(Nil) - b -> Ok(a /. b) - } -} - -/// Adds two floats together. -/// -/// It's the function equivalent of the `+.` operator. -/// This function is useful in higher order functions or pipes. -/// -/// ## Examples -/// -/// ```gleam -/// add(1.0, 2.0) -/// // -> 3.0 -/// ``` -/// -/// ```gleam -/// import gleam/list -/// -/// list.fold([1.0, 2.0, 3.0], 0.0, add) -/// // -> 6.0 -/// ``` -/// -/// ```gleam -/// 3.0 |> add(2.0) -/// // -> 5.0 -/// ``` -/// -pub fn add(a: Float, b: Float) -> Float { - a +. b -} - -/// Multiplies two floats together. -/// -/// It's the function equivalent of the `*.` operator. -/// This function is useful in higher order functions or pipes. -/// -/// ## Examples -/// -/// ```gleam -/// multiply(2.0, 4.0) -/// // -> 8.0 -/// ``` -/// -/// ```gleam -/// import gleam/list -/// -/// list.fold([2.0, 3.0, 4.0], 1.0, multiply) -/// // -> 24.0 -/// ``` -/// -/// ```gleam -/// 3.0 |> multiply(2.0) -/// // -> 6.0 -/// ``` -/// -pub fn multiply(a: Float, b: Float) -> Float { - a *. b -} - -/// Subtracts one float from another. -/// -/// It's the function equivalent of the `-.` operator. -/// This function is useful in higher order functions or pipes. -/// -/// ## Examples -/// -/// ```gleam -/// subtract(3.0, 1.0) -/// // -> 2.0 -/// ``` -/// -/// ```gleam -/// import gleam/list -/// -/// list.fold([1.0, 2.0, 3.0], 10.0, subtract) -/// // -> 4.0 -/// ``` -/// -/// ```gleam -/// 3.0 |> subtract(_, 2.0) -/// // -> 1.0 -/// ``` -/// -/// ```gleam -/// 3.0 |> subtract(2.0, _) -/// // -> -1.0 -/// ``` -/// -pub fn subtract(a: Float, b: Float) -> Float { - a -. b -} diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/function.gleam b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/function.gleam deleted file mode 100644 index 824f373ecbf..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/function.gleam +++ /dev/null @@ -1,74 +0,0 @@ -@deprecated("Use a fn literal instead, it is easier to understand") -pub fn compose(fun1: fn(a) -> b, fun2: fn(b) -> c) -> fn(a) -> c { - fn(a) { fun2(fun1(a)) } -} - -@deprecated("Use the anonymous function syntax instead") -pub fn curry2(fun: fn(a, b) -> value) { - fn(a) { fn(b) { fun(a, b) } } -} - -@deprecated("Use the anonymous function syntax instead") -pub fn curry3(fun: fn(a, b, c) -> value) { - fn(a) { fn(b) { fn(c) { fun(a, b, c) } } } -} - -@deprecated("Use the anonymous function syntax instead") -pub fn curry4(fun: fn(a, b, c, d) -> value) { - fn(a) { fn(b) { fn(c) { fn(d) { fun(a, b, c, d) } } } } -} - -@deprecated("Use the anonymous function syntax instead") -pub fn curry5(fun: fn(a, b, c, d, e) -> value) { - fn(a) { fn(b) { fn(c) { fn(d) { fn(e) { fun(a, b, c, d, e) } } } } } -} - -@deprecated("Use the anonymous function syntax instead") -pub fn curry6(fun: fn(a, b, c, d, e, f) -> value) { - fn(a) { - fn(b) { fn(c) { fn(d) { fn(e) { fn(f) { fun(a, b, c, d, e, f) } } } } } - } -} - -/// Takes a function that takes two arguments and returns a new function that -/// takes the same two arguments, but in reverse order. -/// -pub fn flip(fun: fn(a, b) -> c) -> fn(b, a) -> c { - fn(b, a) { fun(a, b) } -} - -/// Takes a single argument and always returns its input value. -/// -pub fn identity(x: a) -> a { - x -} - -@deprecated("Use a fn literal instead, it is easier to understand") -pub fn constant(value: a) -> fn(b) -> a { - fn(_) { value } -} - -/// Takes an argument and a single function, -/// calls that function with that argument -/// and returns that argument instead of the function return value. -/// Useful for running synchronous side effects in a pipeline. -/// -pub fn tap(arg: a, effect: fn(a) -> b) -> a { - effect(arg) - arg -} - -@deprecated("Use a fn literal instead, it is easier to understand") -pub fn apply1(fun: fn(a) -> value, arg1: a) -> value { - fun(arg1) -} - -@deprecated("Use a fn literal instead, it is easier to understand") -pub fn apply2(fun: fn(a, b) -> value, arg1: a, arg2: b) -> value { - fun(arg1, arg2) -} - -@deprecated("Use a fn literal instead, it is easier to understand") -pub fn apply3(fun: fn(a, b, c) -> value, arg1: a, arg2: b, arg3: c) -> value { - fun(arg1, arg2, arg3) -} diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam deleted file mode 100644 index 5d60b6ec7b9..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/int.gleam +++ /dev/null @@ -1,877 +0,0 @@ -//// Functions for working with integers. -//// -//// ## Division by zero -//// -//// In Erlang division by zero results in a crash, however Gleam does not have -//// partial functions and operators in core so instead division by zero returns -//// zero, a behaviour taken from Pony, Coq, and Lean. -//// -//// This may seem unexpected at first, but it is no less mathematically valid -//// than crashing or returning a special value. Division by zero is undefined -//// in mathematics. - -import gleam/float -import gleam/order.{type Order} - -/// Returns the absolute value of the input. -/// -/// ## Examples -/// -/// ```gleam -/// absolute_value(-12) -/// // -> 12 -/// ``` -/// -/// ```gleam -/// absolute_value(10) -/// // -> 10 -/// ``` -/// -pub fn absolute_value(x: Int) -> Int { - case x >= 0 { - True -> x - False -> x * -1 - } -} - -/// Returns the results of the base being raised to the power of the -/// exponent, as a `Float`. -/// -/// ## Examples -/// -/// ```gleam -/// power(2, -1.0) -/// // -> Ok(0.5) -/// ``` -/// -/// ```gleam -/// power(2, 2.0) -/// // -> Ok(4.0) -/// ``` -/// -/// ```gleam -/// power(8, 1.5) -/// // -> Ok(22.627416997969522) -/// ``` -/// -/// ```gleam -/// 4 |> power(of: 2.0) -/// // -> Ok(16.0) -/// ``` -/// -/// ```gleam -/// power(-1, 0.5) -/// // -> Error(Nil) -/// ``` -/// -pub fn power(base: Int, of exponent: Float) -> Result(Float, Nil) { - base - |> to_float() - |> float.power(exponent) -} - -/// Returns the square root of the input as a `Float`. -/// -/// ## Examples -/// -/// ```gleam -/// square_root(4) -/// // -> Ok(2.0) -/// ``` -/// -/// ```gleam -/// square_root(-16) -/// // -> Error(Nil) -/// ``` -/// -pub fn square_root(x: Int) -> Result(Float, Nil) { - x - |> to_float() - |> float.square_root() -} - -/// Parses a given string as an int if possible. -/// -/// ## Examples -/// -/// ```gleam -/// parse("2") -/// // -> Ok(2) -/// ``` -/// -/// ```gleam -/// parse("ABC") -/// // -> Error(Nil) -/// ``` -/// -pub fn parse(string: String) -> Result(Int, Nil) { - do_parse(string) -} - -@external(erlang, "gleam_stdlib", "parse_int") -@external(javascript, "../gleam_stdlib.mjs", "parse_int") -fn do_parse(a: String) -> Result(Int, Nil) - -/// Parses a given string as an int in a given base if possible. -/// Supports only bases 2 to 36, for values outside of which this function returns an `Error(Nil)`. -/// -/// ## Examples -/// -/// ```gleam -/// base_parse("10", 2) -/// // -> Ok(2) -/// ``` -/// -/// ```gleam -/// base_parse("30", 16) -/// // -> Ok(48) -/// ``` -/// -/// ```gleam -/// base_parse("1C", 36) -/// // -> Ok(48) -/// ``` -/// -/// ```gleam -/// base_parse("48", 1) -/// // -> Error(Nil) -/// ``` -/// -/// ```gleam -/// base_parse("48", 37) -/// // -> Error(Nil) -/// ``` -/// -pub fn base_parse(string: String, base: Int) -> Result(Int, Nil) { - case base >= 2 && base <= 36 { - True -> do_base_parse(string, base) - False -> Error(Nil) - } -} - -@external(erlang, "gleam_stdlib", "int_from_base_string") -@external(javascript, "../gleam_stdlib.mjs", "int_from_base_string") -fn do_base_parse(a: String, b: Int) -> Result(Int, Nil) - -/// Prints a given int to a string. -/// -/// ## Examples -/// -/// ```gleam -/// to_string(2) -/// // -> "2" -/// ``` -/// -pub fn to_string(x: Int) { - do_to_string(x) -} - -@external(erlang, "erlang", "integer_to_binary") -@external(javascript, "../gleam_stdlib.mjs", "to_string") -fn do_to_string(a: Int) -> String - -/// Prints a given int to a string using the base number provided. -/// Supports only bases 2 to 36, for values outside of which this function returns an `Error(Nil)`. -/// For common bases (2, 8, 16, 36), use the `to_baseN` functions. -/// -/// ## Examples -/// -/// ```gleam -/// to_base_string(2, 2) -/// // -> Ok("10") -/// ``` -/// -/// ```gleam -/// to_base_string(48, 16) -/// // -> Ok("30") -/// ``` -/// -/// ```gleam -/// to_base_string(48, 36) -/// // -> Ok("1C") -/// ``` -/// -/// ```gleam -/// to_base_string(48, 1) -/// // -> Error(Nil) -/// ``` -/// -/// ```gleam -/// to_base_string(48, 37) -/// // -> Error(Nil) -/// ``` -/// -pub fn to_base_string(x: Int, base: Int) -> Result(String, Nil) { - case base >= 2 && base <= 36 { - True -> Ok(do_to_base_string(x, base)) - False -> Error(Nil) - } -} - -@external(erlang, "erlang", "integer_to_binary") -@external(javascript, "../gleam_stdlib.mjs", "int_to_base_string") -fn do_to_base_string(a: Int, b: Int) -> String - -/// Prints a given int to a string using base-2. -/// -/// ## Examples -/// -/// ```gleam -/// to_base2(2) -/// // -> "10" -/// ``` -/// -pub fn to_base2(x: Int) -> String { - do_to_base_string(x, 2) -} - -/// Prints a given int to a string using base-8. -/// -/// ## Examples -/// -/// ```gleam -/// to_base8(15) -/// // -> "17" -/// ``` -/// -pub fn to_base8(x: Int) -> String { - do_to_base_string(x, 8) -} - -/// Prints a given int to a string using base-16. -/// -/// ## Examples -/// -/// ```gleam -/// to_base16(48) -/// // -> "30" -/// ``` -/// -pub fn to_base16(x: Int) -> String { - do_to_base_string(x, 16) -} - -/// Prints a given int to a string using base-36. -/// -/// ## Examples -/// -/// ```gleam -/// to_base36(48) -/// // -> "1C" -/// ``` -/// -pub fn to_base36(x: Int) -> String { - do_to_base_string(x, 36) -} - -/// Takes an int and returns its value as a float. -/// -/// ## Examples -/// -/// ```gleam -/// to_float(5) -/// // -> 5.0 -/// ``` -/// -/// ```gleam -/// to_float(0) -/// // -> 0.0 -/// ``` -/// -/// ```gleam -/// to_float(-3) -/// // -> -3.0 -/// ``` -/// -pub fn to_float(x: Int) -> Float { - do_to_float(x) -} - -@external(erlang, "erlang", "float") -@external(javascript, "../gleam_stdlib.mjs", "identity") -fn do_to_float(a: Int) -> Float - -/// Restricts an int between a lower and upper bound. -/// -/// ## Examples -/// -/// ```gleam -/// clamp(40, min: 50, max: 60) -/// // -> 50 -/// ``` -/// -pub fn clamp(x: Int, min min_bound: Int, max max_bound: Int) -> Int { - x - |> min(max_bound) - |> max(min_bound) -} - -/// Compares two ints, returning an order. -/// -/// ## Examples -/// -/// ```gleam -/// compare(2, 3) -/// // -> Lt -/// ``` -/// -/// ```gleam -/// compare(4, 3) -/// // -> Gt -/// ``` -/// -/// ```gleam -/// compare(3, 3) -/// // -> Eq -/// ``` -/// -pub fn compare(a: Int, with b: Int) -> Order { - case a == b { - True -> order.Eq - False -> - case a < b { - True -> order.Lt - False -> order.Gt - } - } -} - -/// Compares two ints, returning the smaller of the two. -/// -/// ## Examples -/// -/// ```gleam -/// min(2, 3) -/// // -> 2 -/// ``` -/// -pub fn min(a: Int, b: Int) -> Int { - case a < b { - True -> a - False -> b - } -} - -/// Compares two ints, returning the larger of the two. -/// -/// ## Examples -/// -/// ```gleam -/// max(2, 3) -/// // -> 3 -/// ``` -/// -pub fn max(a: Int, b: Int) -> Int { - case a > b { - True -> a - False -> b - } -} - -/// Returns whether the value provided is even. -/// -/// ## Examples -/// -/// ```gleam -/// is_even(2) -/// // -> True -/// ``` -/// -/// ```gleam -/// is_even(3) -/// // -> False -/// ``` -/// -pub fn is_even(x: Int) -> Bool { - x % 2 == 0 -} - -/// Returns whether the value provided is odd. -/// -/// ## Examples -/// -/// ```gleam -/// is_odd(3) -/// // -> True -/// ``` -/// -/// ```gleam -/// is_odd(2) -/// // -> False -/// ``` -/// -pub fn is_odd(x: Int) -> Bool { - x % 2 != 0 -} - -/// Returns the negative of the value provided. -/// -/// ## Examples -/// -/// ```gleam -/// negate(1) -/// // -> -1 -/// ``` -/// -pub fn negate(x: Int) -> Int { - -1 * x -} - -/// Sums a list of ints. -/// -/// ## Example -/// -/// ```gleam -/// sum([1, 2, 3]) -/// // -> 6 -/// ``` -/// -pub fn sum(numbers: List(Int)) -> Int { - numbers - |> do_sum(0) -} - -fn do_sum(numbers: List(Int), initial: Int) -> Int { - case numbers { - [] -> initial - [x, ..rest] -> do_sum(rest, x + initial) - } -} - -/// Multiplies a list of ints and returns the product. -/// -/// ## Example -/// -/// ```gleam -/// product([2, 3, 4]) -/// // -> 24 -/// ``` -/// -pub fn product(numbers: List(Int)) -> Int { - case numbers { - [] -> 1 - _ -> do_product(numbers, 1) - } -} - -fn do_product(numbers: List(Int), initial: Int) -> Int { - case numbers { - [] -> initial - [x, ..rest] -> do_product(rest, x * initial) - } -} - -/// Splits an integer into its digit representation in the specified base. -/// Returns an error if the base is less than 2. -/// -/// ## Examples -/// -/// ```gleam -/// digits(234, 10) -/// // -> Ok([2,3,4]) -/// ``` -/// -/// ```gleam -/// digits(234, 1) -/// // -> Error(Nil) -/// ``` -/// -pub fn digits(x: Int, base: Int) -> Result(List(Int), Nil) { - case base < 2 { - True -> Error(Nil) - False -> Ok(do_digits(x, base, [])) - } -} - -fn do_digits(x: Int, base: Int, acc: List(Int)) -> List(Int) { - case absolute_value(x) < base { - True -> [x, ..acc] - False -> do_digits(x / base, base, [x % base, ..acc]) - } -} - -/// Joins a list of digits into a single value. -/// Returns an error if the base is less than 2 or if the list contains a digit greater than or equal to the specified base. -/// -/// ## Examples -/// -/// ```gleam -/// undigits([2,3,4], 10) -/// // -> Ok(234) -/// ``` -/// -/// ```gleam -/// undigits([2,3,4], 1) -/// // -> Error(Nil) -/// ``` -/// -/// ```gleam -/// undigits([2,3,4], 2) -/// // -> Error(Nil) -/// ``` -/// -pub fn undigits(numbers: List(Int), base: Int) -> Result(Int, Nil) { - case base < 2 { - True -> Error(Nil) - False -> do_undigits(numbers, base, 0) - } -} - -fn do_undigits(numbers: List(Int), base: Int, acc: Int) -> Result(Int, Nil) { - case numbers { - [] -> Ok(acc) - [digit, ..] if digit >= base -> Error(Nil) - [digit, ..rest] -> do_undigits(rest, base, acc * base + digit) - } -} - -/// Generates a random int between zero and the given maximum. -/// -/// The lower number is inclusive, the upper number is exclusive. -/// -/// ## Examples -/// -/// ```gleam -/// random(10) -/// // -> 4 -/// ``` -/// -/// ```gleam -/// random(1) -/// // -> 0 -/// ``` -/// -/// ```gleam -/// random(-1) -/// // -> -1 -/// ``` -/// -pub fn random(max: Int) -> Int { - { float.random() *. to_float(max) } - |> float.floor() - |> float.round() -} - -/// Performs a truncated integer division. -/// -/// Returns division of the inputs as a `Result`: If the given divisor equals -/// `0`, this function returns an `Error`. -/// -/// ## Examples -/// -/// ```gleam -/// divide(0, 1) -/// // -> Ok(0) -/// ``` -/// -/// ```gleam -/// divide(1, 0) -/// // -> Error(Nil) -/// ``` -/// -/// ```gleam -/// divide(5, 2) -/// // -> Ok(2) -/// ``` -/// -/// ```gleam -/// divide(-99, 2) -/// // -> Ok(-49) -/// ``` -/// -pub fn divide(dividend: Int, by divisor: Int) -> Result(Int, Nil) { - case divisor { - 0 -> Error(Nil) - divisor -> Ok(dividend / divisor) - } -} - -/// Computes the remainder of an integer division of inputs as a `Result`. -/// -/// Returns division of the inputs as a `Result`: If the given divisor equals -/// `0`, this function returns an `Error`. -/// -/// Most the time you will want to use the `%` operator instead of this -/// function. -/// -/// ## Examples -/// -/// ```gleam -/// remainder(3, 2) -/// // -> Ok(1) -/// ``` -/// -/// ```gleam -/// remainder(1, 0) -/// // -> Error(Nil) -/// ``` -/// -/// ```gleam -/// remainder(10, -1) -/// // -> Ok(0) -/// ``` -/// -/// ```gleam -/// remainder(13, by: 3) -/// // -> Ok(1) -/// ``` -/// -/// ```gleam -/// remainder(-13, by: 3) -/// // -> Ok(-1) -/// ``` -/// -/// ```gleam -/// remainder(13, by: -3) -/// // -> Ok(1) -/// ``` -/// -/// ```gleam -/// remainder(-13, by: -3) -/// // -> Ok(-1) -/// ``` -/// -pub fn remainder(dividend: Int, by divisor: Int) -> Result(Int, Nil) { - case divisor { - 0 -> Error(Nil) - divisor -> Ok(dividend % divisor) - } -} - -/// Computes the modulo of an integer division of inputs as a `Result`. -/// -/// Returns division of the inputs as a `Result`: If the given divisor equals -/// `0`, this function returns an `Error`. -/// -/// Most the time you will want to use the `%` operator instead of this -/// function. -/// -/// ## Examples -/// -/// ```gleam -/// modulo(3, 2) -/// // -> Ok(1) -/// ``` -/// -/// ```gleam -/// modulo(1, 0) -/// // -> Error(Nil) -/// ``` -/// -/// ```gleam -/// modulo(10, -1) -/// // -> Ok(0) -/// ``` -/// -/// ```gleam -/// modulo(13, by: 3) -/// // -> Ok(1) -/// ``` -/// -/// ```gleam -/// modulo(-13, by: 3) -/// // -> Ok(2) -/// ``` -/// -pub fn modulo(dividend: Int, by divisor: Int) -> Result(Int, Nil) { - case divisor { - 0 -> Error(Nil) - _ -> { - let remainder = dividend % divisor - case remainder * divisor < 0 { - True -> Ok(remainder + divisor) - False -> Ok(remainder) - } - } - } -} - -/// Performs a *floored* integer division, which means that the result will -/// always be rounded towards negative infinity. -/// -/// If you want to perform truncated integer division (rounding towards zero), -/// use `int.divide()` or the `/` operator instead. -/// -/// Returns division of the inputs as a `Result`: If the given divisor equals -/// `0`, this function returns an `Error`. -/// -/// ## Examples -/// -/// ```gleam -/// floor_divide(1, 0) -/// // -> Error(Nil) -/// ``` -/// -/// ```gleam -/// floor_divide(5, 2) -/// // -> Ok(2) -/// ``` -/// -/// ```gleam -/// floor_divide(6, -4) -/// // -> Ok(-2) -/// ``` -/// -/// ```gleam -/// floor_divide(-99, 2) -/// // -> Ok(-50) -/// ``` -/// -pub fn floor_divide(dividend: Int, by divisor: Int) -> Result(Int, Nil) { - case divisor { - 0 -> Error(Nil) - divisor -> - case dividend * divisor < 0 && dividend % divisor != 0 { - True -> Ok(dividend / divisor - 1) - False -> Ok(dividend / divisor) - } - } -} - -/// Adds two integers together. -/// -/// It's the function equivalent of the `+` operator. -/// This function is useful in higher order functions or pipes. -/// -/// ## Examples -/// -/// ```gleam -/// add(1, 2) -/// // -> 3 -/// ``` -/// -/// ```gleam -/// import gleam/list -/// list.fold([1, 2, 3], 0, add) -/// // -> 6 -/// ``` -/// -/// ```gleam -/// 3 |> add(2) -/// // -> 5 -/// ``` -/// -pub fn add(a: Int, b: Int) -> Int { - a + b -} - -/// Multiplies two integers together. -/// -/// It's the function equivalent of the `*` operator. -/// This function is useful in higher order functions or pipes. -/// -/// ## Examples -/// -/// ```gleam -/// multiply(2, 4) -/// // -> 8 -/// ``` -/// -/// ```gleam -/// import gleam/list -/// -/// list.fold([2, 3, 4], 1, multiply) -/// // -> 24 -/// ``` -/// -/// ```gleam -/// 3 |> multiply(2) -/// // -> 6 -/// ``` -/// -pub fn multiply(a: Int, b: Int) -> Int { - a * b -} - -/// Subtracts one int from another. -/// -/// It's the function equivalent of the `-` operator. -/// This function is useful in higher order functions or pipes. -/// -/// ## Examples -/// -/// ```gleam -/// subtract(3, 1) -/// // -> 2 -/// ``` -/// -/// ```gleam -/// import gleam/list -/// -/// list.fold([1, 2, 3], 10, subtract) -/// // -> 4 -/// ``` -/// -/// ```gleam -/// 3 |> subtract(2) -/// // -> 1 -/// ``` -/// -/// ```gleam -/// 3 |> subtract(2, _) -/// // -> -1 -/// ``` -/// -pub fn subtract(a: Int, b: Int) -> Int { - a - b -} - -/// Calculates the bitwise AND of its arguments. -/// -/// The exact behaviour of this function depends on the target platform. -/// On Erlang it is equivalent to bitwise operations on ints, on JavaScript it -/// is equivalent to bitwise operations on big-ints. -/// -@external(erlang, "erlang", "band") -@external(javascript, "../gleam_stdlib.mjs", "bitwise_and") -pub fn bitwise_and(x: Int, y: Int) -> Int - -/// Calculates the bitwise NOT of its argument. -/// -/// The exact behaviour of this function depends on the target platform. -/// On Erlang it is equivalent to bitwise operations on ints, on JavaScript it -/// is equivalent to bitwise operations on big-ints. -/// -@external(erlang, "erlang", "bnot") -@external(javascript, "../gleam_stdlib.mjs", "bitwise_not") -pub fn bitwise_not(x: Int) -> Int - -/// Calculates the bitwise OR of its arguments. -/// -/// The exact behaviour of this function depends on the target platform. -/// On Erlang it is equivalent to bitwise operations on ints, on JavaScript it -/// is equivalent to bitwise operations on big-ints. -/// -@external(erlang, "erlang", "bor") -@external(javascript, "../gleam_stdlib.mjs", "bitwise_or") -pub fn bitwise_or(x: Int, y: Int) -> Int - -/// Calculates the bitwise XOR of its arguments. -/// -/// The exact behaviour of this function depends on the target platform. -/// On Erlang it is equivalent to bitwise operations on ints, on JavaScript it -/// is equivalent to bitwise operations on big-ints. -/// -@external(erlang, "erlang", "bxor") -@external(javascript, "../gleam_stdlib.mjs", "bitwise_exclusive_or") -pub fn bitwise_exclusive_or(x: Int, y: Int) -> Int - -/// Calculates the result of an arithmetic left bitshift. -/// -/// The exact behaviour of this function depends on the target platform. -/// On Erlang it is equivalent to bitwise operations on ints, on JavaScript it -/// is equivalent to bitwise operations on big-ints. -/// -@external(erlang, "erlang", "bsl") -@external(javascript, "../gleam_stdlib.mjs", "bitwise_shift_left") -pub fn bitwise_shift_left(x: Int, y: Int) -> Int - -/// Calculates the result of an arithmetic right bitshift. -/// -/// The exact behaviour of this function depends on the target platform. -/// On Erlang it is equivalent to bitwise operations on ints, on JavaScript it -/// is equivalent to bitwise operations on big-ints. -/// -@external(erlang, "erlang", "bsr") -@external(javascript, "../gleam_stdlib.mjs", "bitwise_shift_right") -pub fn bitwise_shift_right(x: Int, y: Int) -> Int diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/io.gleam b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/io.gleam deleted file mode 100644 index 0f16cc3af58..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/io.gleam +++ /dev/null @@ -1,118 +0,0 @@ -import gleam/string - -/// Writes a string to standard output (stdout). -/// -/// If you want your output to be printed on its own line see `println`. -/// -/// ## Example -/// -/// ```gleam -/// io.print("Hi mum") -/// // -> Nil -/// // Hi mum -/// ``` -/// -pub fn print(string: String) -> Nil { - do_print(string) -} - -@external(erlang, "gleam_stdlib", "print") -@external(javascript, "../gleam_stdlib.mjs", "print") -fn do_print(string string: String) -> Nil - -/// Writes a string to standard error (stderr). -/// -/// If you want your output to be printed on its own line see `println_error`. -/// -/// ## Example -/// -/// ``` -/// io.print_error("Hi pop") -/// // -> Nil -/// // Hi pop -/// ``` -/// -pub fn print_error(string: String) -> Nil { - do_print_error(string) -} - -@external(erlang, "gleam_stdlib", "print_error") -@external(javascript, "../gleam_stdlib.mjs", "print_error") -fn do_print_error(string string: String) -> Nil - -/// Writes a string to standard output (stdout), appending a newline to the end. -/// -/// ## Example -/// -/// ```gleam -/// io.println("Hi mum") -/// // -> Nil -/// // Hi mum -/// ``` -/// -pub fn println(string: String) -> Nil { - do_println(string) -} - -@external(erlang, "gleam_stdlib", "println") -@external(javascript, "../gleam_stdlib.mjs", "console_log") -fn do_println(string string: String) -> Nil - -/// Writes a string to standard error (stderr), appending a newline to the end. -/// -/// ## Example -/// -/// ```gleam -/// io.println_error("Hi pop") -/// // -> Nil -/// // Hi pop -/// ``` -/// -pub fn println_error(string: String) -> Nil { - do_println_error(string) -} - -@external(erlang, "gleam_stdlib", "println_error") -@external(javascript, "../gleam_stdlib.mjs", "console_error") -fn do_println_error(string string: String) -> Nil - -/// Writes a value to standard error (stderr) yielding Gleam syntax. -/// -/// The value is returned after being printed so it can be used in pipelines. -/// -/// ## Example -/// -/// ```gleam -/// debug("Hi mum") -/// // -> "Hi mum" -/// // <<"Hi mum">> -/// ``` -/// -/// ```gleam -/// debug(Ok(1)) -/// // -> Ok(1) -/// // {ok, 1} -/// ``` -/// -/// ```gleam -/// import gleam/list -/// -/// [1, 2] -/// |> list.map(fn(x) { x + 1 }) -/// |> debug -/// |> list.map(fn(x) { x * 2 }) -/// // -> [4, 6] -/// // [2, 3] -/// ``` -/// -pub fn debug(term: anything) -> anything { - term - |> string.inspect - |> do_debug_println - - term -} - -@external(erlang, "gleam_stdlib", "println_error") -@external(javascript, "../gleam_stdlib.mjs", "print_debug") -fn do_debug_println(string string: String) -> Nil diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam deleted file mode 100644 index 3232a12f55f..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/iterator.gleam +++ /dev/null @@ -1,1628 +0,0 @@ -import gleam/dict.{type Dict} -import gleam/int -import gleam/list -import gleam/option.{type Option, None, Some} -import gleam/order - -// Internal private representation of an Iterator -type Action(element) { - // Dedicated to Electric Six - // https://youtu.be/_30t2dzEgiw?t=162 - Stop - Continue(element, fn() -> Action(element)) -} - -/// An iterator is a lazily evaluated sequence of element. -/// -/// Iterators are useful when working with collections that are too large to -/// fit in memory (or those that are infinite in size) as they only require the -/// elements currently being processed to be in memory. -/// -/// As a lazy data structure no work is done when an iterator is filtered, -/// mapped, etc, instead a new iterator is returned with these transformations -/// applied to the stream. Once the stream has all the required transformations -/// applied it can be evaluated using functions such as `fold` and `to_list`. -/// -pub opaque type Iterator(element) { - Iterator(continuation: fn() -> Action(element)) -} - -// Public API for iteration -pub type Step(element, accumulator) { - Next(element: element, accumulator: accumulator) - Done -} - -// Shortcut for an empty iterator. -fn stop() -> Action(element) { - Stop -} - -// Creating Iterators -fn do_unfold( - initial: acc, - f: fn(acc) -> Step(element, acc), -) -> fn() -> Action(element) { - fn() { - case f(initial) { - Next(x, acc) -> Continue(x, do_unfold(acc, f)) - Done -> Stop - } - } -} - -/// Creates an iterator from a given function and accumulator. -/// -/// The function is called on the accumulator and returns either `Done`, -/// indicating the iterator has no more elements, or `Next` which contains a -/// new element and accumulator. The element is yielded by the iterator and the -/// new accumulator is used with the function to compute the next element in -/// the sequence. -/// -/// ## Examples -/// -/// ```gleam -/// unfold(from: 5, with: fn(n) { -/// case n { -/// 0 -> Done -/// n -> Next(element: n, accumulator: n - 1) -/// } -/// }) -/// |> to_list -/// // -> [5, 4, 3, 2, 1] -/// ``` -/// -pub fn unfold( - from initial: acc, - with f: fn(acc) -> Step(element, acc), -) -> Iterator(element) { - initial - |> do_unfold(f) - |> Iterator -} - -/// Creates an iterator that yields values created by calling a given function -/// repeatedly. -/// -/// ```gleam -/// repeatedly(fn() { 7 }) -/// |> take(3) -/// |> to_list -/// // -> [7, 7, 7] -/// ``` -/// -pub fn repeatedly(f: fn() -> element) -> Iterator(element) { - unfold(Nil, fn(_) { Next(f(), Nil) }) -} - -/// Creates an iterator that returns the same value infinitely. -/// -/// ## Examples -/// -/// ```gleam -/// repeat(10) -/// |> take(4) -/// |> to_list -/// // -> [10, 10, 10, 10] -/// ``` -/// -pub fn repeat(x: element) -> Iterator(element) { - repeatedly(fn() { x }) -} - -/// Creates an iterator that yields each element from the given list. -/// -/// ## Examples -/// -/// ```gleam -/// from_list([1, 2, 3, 4]) -/// |> to_list -/// // -> [1, 2, 3, 4] -/// ``` -/// -pub fn from_list(list: List(element)) -> Iterator(element) { - let yield = fn(acc) { - case acc { - [] -> Done - [head, ..tail] -> Next(head, tail) - } - } - unfold(list, yield) -} - -// Consuming Iterators -fn do_transform( - continuation: fn() -> Action(a), - state: acc, - f: fn(acc, a) -> Step(b, acc), -) -> fn() -> Action(b) { - fn() { - case continuation() { - Stop -> Stop - Continue(el, next) -> - case f(state, el) { - Done -> Stop - Next(yield, next_state) -> - Continue(yield, do_transform(next, next_state, f)) - } - } - } -} - -/// Creates an iterator from an existing iterator -/// and a stateful function that may short-circuit. -/// -/// `f` takes arguments `acc` for current state and `el` for current element from underlying iterator, -/// and returns either `Next` with yielded element and new state value, or `Done` to halt the iterator. -/// -/// ## Examples -/// -/// Approximate implementation of `index` in terms of `transform`: -/// -/// ```gleam -/// from_list(["a", "b", "c"]) -/// |> transform(0, fn(i, el) { Next(#(i, el), i + 1) }) -/// |> to_list -/// // -> [#(0, "a"), #(1, "b"), #(2, "c")] -/// ``` -/// -pub fn transform( - over iterator: Iterator(a), - from initial: acc, - with f: fn(acc, a) -> Step(b, acc), -) -> Iterator(b) { - do_transform(iterator.continuation, initial, f) - |> Iterator -} - -fn do_fold( - continuation: fn() -> Action(e), - f: fn(acc, e) -> acc, - accumulator: acc, -) -> acc { - case continuation() { - Continue(elem, next) -> do_fold(next, f, f(accumulator, elem)) - Stop -> accumulator - } -} - -/// Reduces an iterator of elements into a single value by calling a given -/// function on each element in turn. -/// -/// If called on an iterator of infinite length then this function will never -/// return. -/// -/// If you do not care about the end value and only wish to evaluate the -/// iterator for side effects consider using the `run` function instead. -/// -/// ## Examples -/// -/// ```gleam -/// from_list([1, 2, 3, 4]) -/// |> fold(from: 0, with: fn(acc, element) { element + acc }) -/// // -> 10 -/// ``` -/// -pub fn fold( - over iterator: Iterator(e), - from initial: acc, - with f: fn(acc, e) -> acc, -) -> acc { - iterator.continuation - |> do_fold(f, initial) -} - -// TODO: test -/// Evaluates all elements emitted by the given iterator. This function is useful for when -/// you wish to trigger any side effects that would occur when evaluating -/// the iterator. -/// -pub fn run(iterator: Iterator(e)) -> Nil { - fold(iterator, Nil, fn(_, _) { Nil }) -} - -/// Evaluates an iterator and returns all the elements as a list. -/// -/// If called on an iterator of infinite length then this function will never -/// return. -/// -/// ## Examples -/// -/// ```gleam -/// from_list([1, 2, 3]) -/// |> map(fn(x) { x * 2 }) -/// |> to_list -/// // -> [2, 4, 6] -/// ``` -/// -pub fn to_list(iterator: Iterator(element)) -> List(element) { - iterator - |> fold([], fn(acc, e) { [e, ..acc] }) - |> list.reverse -} - -/// Eagerly accesses the first value of an iterator, returning a `Next` -/// that contains the first value and the rest of the iterator. -/// -/// If called on an empty iterator, `Done` is returned. -/// -/// ## Examples -/// -/// ```gleam -/// let assert Next(first, rest) = from_list([1, 2, 3, 4]) |> step -/// -/// first -/// // -> 1 -/// -/// rest |> to_list -/// // -> [2, 3, 4] -/// ``` -/// -/// ```gleam -/// empty() |> step -/// // -> Done -/// ``` -/// -pub fn step(iterator: Iterator(e)) -> Step(e, Iterator(e)) { - case iterator.continuation() { - Stop -> Done - Continue(e, a) -> Next(e, Iterator(a)) - } -} - -fn do_take(continuation: fn() -> Action(e), desired: Int) -> fn() -> Action(e) { - fn() { - case desired > 0 { - False -> Stop - True -> - case continuation() { - Stop -> Stop - Continue(e, next) -> Continue(e, do_take(next, desired - 1)) - } - } - } -} - -/// Creates an iterator that only yields the first `desired` elements. -/// -/// If the iterator does not have enough elements all of them are yielded. -/// -/// ## Examples -/// -/// ```gleam -/// from_list([1, 2, 3, 4, 5]) -/// |> take(up_to: 3) -/// |> to_list -/// // -> [1, 2, 3] -/// ``` -/// -/// ```gleam -/// from_list([1, 2]) -/// |> take(up_to: 3) -/// |> to_list -/// // -> [1, 2] -/// ``` -/// -pub fn take(from iterator: Iterator(e), up_to desired: Int) -> Iterator(e) { - iterator.continuation - |> do_take(desired) - |> Iterator -} - -fn do_drop(continuation: fn() -> Action(e), desired: Int) -> Action(e) { - case continuation() { - Stop -> Stop - Continue(e, next) -> - case desired > 0 { - True -> do_drop(next, desired - 1) - False -> Continue(e, next) - } - } -} - -/// Evaluates and discards the first N elements in an iterator, returning a new -/// iterator. -/// -/// If the iterator does not have enough elements an empty iterator is -/// returned. -/// -/// This function does not evaluate the elements of the iterator, the -/// computation is performed when the iterator is later run. -/// -/// ## Examples -/// -/// ```gleam -/// from_list([1, 2, 3, 4, 5]) -/// |> drop(up_to: 3) -/// |> to_list -/// // -> [4, 5] -/// ``` -/// -/// ```gleam -/// from_list([1, 2]) -/// |> drop(up_to: 3) -/// |> to_list -/// // -> [] -/// ``` -/// -pub fn drop(from iterator: Iterator(e), up_to desired: Int) -> Iterator(e) { - fn() { do_drop(iterator.continuation, desired) } - |> Iterator -} - -fn do_map(continuation: fn() -> Action(a), f: fn(a) -> b) -> fn() -> Action(b) { - fn() { - case continuation() { - Stop -> Stop - Continue(e, continuation) -> Continue(f(e), do_map(continuation, f)) - } - } -} - -/// Creates an iterator from an existing iterator and a transformation function. -/// -/// Each element in the new iterator will be the result of calling the given -/// function on the elements in the given iterator. -/// -/// This function does not evaluate the elements of the iterator, the -/// computation is performed when the iterator is later run. -/// -/// ## Examples -/// -/// ```gleam -/// from_list([1, 2, 3]) -/// |> map(fn(x) { x * 2 }) -/// |> to_list -/// // -> [2, 4, 6] -/// ``` -/// -pub fn map(over iterator: Iterator(a), with f: fn(a) -> b) -> Iterator(b) { - iterator.continuation - |> do_map(f) - |> Iterator -} - -fn do_map2( - continuation1: fn() -> Action(a), - continuation2: fn() -> Action(b), - with fun: fn(a, b) -> c, -) -> fn() -> Action(c) { - fn() { - case continuation1() { - Stop -> Stop - Continue(a, next_a) -> - case continuation2() { - Stop -> Stop - Continue(b, next_b) -> - Continue(fun(a, b), do_map2(next_a, next_b, fun)) - } - } - } -} - -/// Combines two iterators into a single one using the given function. -/// -/// If an iterator is longer than the other the extra elements are dropped. -/// -/// This function does not evaluate the elements of the two iterators, the -/// computation is performed when the resulting iterator is later run. -/// -/// ## Examples -/// -/// ```gleam -/// let first = from_list([1, 2, 3]) -/// let second = from_list([4, 5, 6]) -/// map2(first, second, fn(x, y) { x + y }) |> to_list -/// // -> [5, 7, 9] -/// ``` -/// -/// ```gleam -/// let first = from_list([1, 2]) -/// let second = from_list(["a", "b", "c"]) -/// map2(first, second, fn(i, x) { #(i, x) }) |> to_list -/// // -> [#(1, "a"), #(2, "b")] -/// ``` -/// -pub fn map2( - iterator1: Iterator(a), - iterator2: Iterator(b), - with fun: fn(a, b) -> c, -) -> Iterator(c) { - do_map2(iterator1.continuation, iterator2.continuation, fun) - |> Iterator -} - -fn do_append(first: fn() -> Action(a), second: fn() -> Action(a)) -> Action(a) { - case first() { - Continue(e, first) -> Continue(e, fn() { do_append(first, second) }) - Stop -> second() - } -} - -/// Appends two iterators, producing a new iterator. -/// -/// This function does not evaluate the elements of the iterators, the -/// computation is performed when the resulting iterator is later run. -/// -/// ## Examples -/// -/// ```gleam -/// from_list([1, 2]) -/// |> append(from_list([3, 4])) -/// |> to_list -/// // -> [1, 2, 3, 4] -/// ``` -/// -pub fn append(to first: Iterator(a), suffix second: Iterator(a)) -> Iterator(a) { - fn() { do_append(first.continuation, second.continuation) } - |> Iterator -} - -fn do_flatten(flattened: fn() -> Action(Iterator(a))) -> Action(a) { - case flattened() { - Stop -> Stop - Continue(it, next_iterator) -> - do_append(it.continuation, fn() { do_flatten(next_iterator) }) - } -} - -/// Flattens an iterator of iterators, creating a new iterator. -/// -/// This function does not evaluate the elements of the iterator, the -/// computation is performed when the iterator is later run. -/// -/// ## Examples -/// -/// ```gleam -/// from_list([[1, 2], [3, 4]]) -/// |> map(from_list) -/// |> flatten -/// |> to_list -/// // -> [1, 2, 3, 4] -/// ``` -/// -pub fn flatten(iterator: Iterator(Iterator(a))) -> Iterator(a) { - fn() { do_flatten(iterator.continuation) } - |> Iterator -} - -/// Joins a list of iterators into a single iterator. -/// -/// This function does not evaluate the elements of the iterator, the -/// computation is performed when the iterator is later run. -/// -/// ## Examples -/// -/// ```gleam -/// [[1, 2], [3, 4]] -/// |> map(from_list) -/// |> concat -/// |> to_list -/// // -> [1, 2, 3, 4] -/// ``` -/// -pub fn concat(iterators: List(Iterator(a))) -> Iterator(a) { - flatten(from_list(iterators)) -} - -/// Creates an iterator from an existing iterator and a transformation function. -/// -/// Each element in the new iterator will be the result of calling the given -/// function on the elements in the given iterator and then flattening the -/// results. -/// -/// This function does not evaluate the elements of the iterator, the -/// computation is performed when the iterator is later run. -/// -/// ## Examples -/// -/// ```gleam -/// from_list([1, 2]) -/// |> flat_map(fn(x) { from_list([x, x + 1]) }) -/// |> to_list -/// // -> [1, 2, 2, 3] -/// ``` -/// -pub fn flat_map( - over iterator: Iterator(a), - with f: fn(a) -> Iterator(b), -) -> Iterator(b) { - iterator - |> map(f) - |> flatten -} - -fn do_filter( - continuation: fn() -> Action(e), - predicate: fn(e) -> Bool, -) -> Action(e) { - case continuation() { - Stop -> Stop - Continue(e, iterator) -> - case predicate(e) { - True -> Continue(e, fn() { do_filter(iterator, predicate) }) - False -> do_filter(iterator, predicate) - } - } -} - -/// Creates an iterator from an existing iterator and a predicate function. -/// -/// The new iterator will contain elements from the first iterator for which -/// the given function returns `True`. -/// -/// This function does not evaluate the elements of the iterator, the -/// computation is performed when the iterator is later run. -/// -/// ## Examples -/// -/// ```gleam -/// import gleam/int -/// -/// from_list([1, 2, 3, 4]) -/// |> filter(int.is_even) -/// |> to_list -/// // -> [2, 4] -/// ``` -/// -pub fn filter( - iterator: Iterator(a), - keeping predicate: fn(a) -> Bool, -) -> Iterator(a) { - fn() { do_filter(iterator.continuation, predicate) } - |> Iterator -} - -fn do_filter_map( - continuation: fn() -> Action(a), - f: fn(a) -> Result(b, c), -) -> Action(b) { - case continuation() { - Stop -> Stop - Continue(e, next) -> - case f(e) { - Ok(e) -> Continue(e, fn() { do_filter_map(next, f) }) - Error(_) -> do_filter_map(next, f) - } - } -} - -/// Creates an iterator from an existing iterator and a transforming predicate function. -/// -/// The new iterator will contain elements from the first iterator for which -/// the given function returns `Ok`, transformed to the value inside the `Ok`. -/// -/// This function does not evaluate the elements of the iterator, the -/// computation is performed when the iterator is later run. -/// -/// ## Examples -/// -/// ```gleam -/// import gleam/string -/// import gleam/int -/// -/// "a1b2c3d4e5f" -/// |> string.to_graphemes -/// |> from_list -/// |> filter_map(int.parse) -/// |> to_list -/// // -> [1, 2, 3, 4, 5] -/// ``` -/// -pub fn filter_map( - iterator: Iterator(a), - keeping_with f: fn(a) -> Result(b, c), -) -> Iterator(b) { - fn() { do_filter_map(iterator.continuation, f) } - |> Iterator -} - -/// Creates an iterator that repeats a given iterator infinitely. -/// -/// ## Examples -/// -/// ```gleam -/// from_list([1, 2]) -/// |> cycle -/// |> take(6) -/// |> to_list -/// // -> [1, 2, 1, 2, 1, 2] -/// ``` -/// -pub fn cycle(iterator: Iterator(a)) -> Iterator(a) { - repeat(iterator) - |> flatten -} - -/// Creates an iterator of ints, starting at a given start int and stepping by -/// one to a given end int. -/// -/// ## Examples -/// -/// ```gleam -/// range(from: 1, to: 5) |> to_list -/// // -> [1, 2, 3, 4, 5] -/// ``` -/// -/// ```gleam -/// range(from: 1, to: -2) |> to_list -/// // -> [1, 0, -1, -2] -/// ``` -/// -/// ```gleam -/// range(from: 0, to: 0) |> to_list -/// // -> [0] -/// ``` -/// -pub fn range(from start: Int, to stop: Int) -> Iterator(Int) { - case int.compare(start, stop) { - order.Eq -> once(fn() { start }) - order.Gt -> - unfold(from: start, with: fn(current) { - case current < stop { - False -> Next(current, current - 1) - True -> Done - } - }) - - order.Lt -> - unfold(from: start, with: fn(current) { - case current > stop { - False -> Next(current, current + 1) - True -> Done - } - }) - } -} - -fn do_find(continuation: fn() -> Action(a), f: fn(a) -> Bool) -> Result(a, Nil) { - case continuation() { - Stop -> Error(Nil) - Continue(e, next) -> - case f(e) { - True -> Ok(e) - False -> do_find(next, f) - } - } -} - -/// Finds the first element in a given iterator for which the given function returns -/// `True`. -/// -/// Returns `Error(Nil)` if the function does not return `True` for any of the -/// elements. -/// -/// ## Examples -/// -/// ```gleam -/// find(from_list([1, 2, 3]), fn(x) { x > 2 }) -/// // -> Ok(3) -/// ``` -/// -/// ```gleam -/// find(from_list([1, 2, 3]), fn(x) { x > 4 }) -/// // -> Error(Nil) -/// ``` -/// -/// ```gleam -/// find(empty(), fn(_) { True }) -/// // -> Error(Nil) -/// ``` -/// -pub fn find( - in haystack: Iterator(a), - one_that is_desired: fn(a) -> Bool, -) -> Result(a, Nil) { - haystack.continuation - |> do_find(is_desired) -} - -fn do_find_map( - continuation: fn() -> Action(a), - f: fn(a) -> Result(b, c), -) -> Result(b, Nil) { - case continuation() { - Stop -> Error(Nil) - Continue(e, next) -> - case f(e) { - Ok(e) -> Ok(e) - Error(_) -> do_find_map(next, f) - } - } -} - -/// Finds the first element in a given iterator -/// for which the given function returns `Ok(new_value)`, -/// then returns the wrapped `new_value`. -/// -/// Returns `Error(Nil)` if no such element is found. -/// -/// ## Examples -/// -/// ```gleam -/// find_map(from_list(["a", "1", "2"]), int.parse) -/// // -> Ok(1) -/// ``` -/// -/// ```gleam -/// find_map(from_list(["a", "b", "c"]), int.parse) -/// // -> Error(Nil) -/// ``` -/// -/// ```gleam -/// find_map(from_list([]), int.parse) -/// // -> Error(Nil) -/// ``` -/// -pub fn find_map( - in haystack: Iterator(a), - one_that is_desired: fn(a) -> Result(b, c), -) -> Result(b, Nil) { - haystack.continuation - |> do_find_map(is_desired) -} - -fn do_index( - continuation: fn() -> Action(element), - next: Int, -) -> fn() -> Action(#(element, Int)) { - fn() { - case continuation() { - Stop -> Stop - Continue(e, continuation) -> - Continue(#(e, next), do_index(continuation, next + 1)) - } - } -} - -/// Wraps values yielded from an iterator with indices, starting from 0. -/// -/// ## Examples -/// -/// ```gleam -/// from_list(["a", "b", "c"]) |> index |> to_list -/// // -> [#("a", 0), #("b", 1), #("c", 2)] -/// ``` -/// -pub fn index(over iterator: Iterator(element)) -> Iterator(#(element, Int)) { - iterator.continuation - |> do_index(0) - |> Iterator -} - -/// Creates an iterator that infinitely applies a function to a value. -/// -/// ## Examples -/// -/// ```gleam -/// iterate(1, fn(n) { n * 3 }) |> take(5) |> to_list -/// // -> [1, 3, 9, 27, 81] -/// ``` -/// -pub fn iterate( - from initial: element, - with f: fn(element) -> element, -) -> Iterator(element) { - unfold(initial, fn(element) { Next(element, f(element)) }) -} - -fn do_take_while( - continuation: fn() -> Action(element), - predicate: fn(element) -> Bool, -) -> fn() -> Action(element) { - fn() { - case continuation() { - Stop -> Stop - Continue(e, next) -> - case predicate(e) { - False -> Stop - True -> Continue(e, do_take_while(next, predicate)) - } - } - } -} - -/// Creates an iterator that yields elements while the predicate returns `True`. -/// -/// ## Examples -/// -/// ```gleam -/// from_list([1, 2, 3, 2, 4]) -/// |> take_while(satisfying: fn(x) { x < 3 }) -/// |> to_list -/// // -> [1, 2] -/// ``` -/// -pub fn take_while( - in iterator: Iterator(element), - satisfying predicate: fn(element) -> Bool, -) -> Iterator(element) { - iterator.continuation - |> do_take_while(predicate) - |> Iterator -} - -fn do_drop_while( - continuation: fn() -> Action(element), - predicate: fn(element) -> Bool, -) -> Action(element) { - case continuation() { - Stop -> Stop - Continue(e, next) -> - case predicate(e) { - False -> Continue(e, next) - True -> do_drop_while(next, predicate) - } - } -} - -/// Creates an iterator that drops elements while the predicate returns `True`, -/// and then yields the remaining elements. -/// -/// ## Examples -/// -/// ```gleam -/// from_list([1, 2, 3, 4, 2, 5]) -/// |> drop_while(satisfying: fn(x) { x < 4 }) -/// |> to_list -/// // -> [4, 2, 5] -/// ``` -/// -pub fn drop_while( - in iterator: Iterator(element), - satisfying predicate: fn(element) -> Bool, -) -> Iterator(element) { - fn() { do_drop_while(iterator.continuation, predicate) } - |> Iterator -} - -fn do_scan( - continuation: fn() -> Action(element), - f: fn(acc, element) -> acc, - accumulator: acc, -) -> fn() -> Action(acc) { - fn() { - case continuation() { - Stop -> Stop - Continue(el, next) -> { - let accumulated = f(accumulator, el) - Continue(accumulated, do_scan(next, f, accumulated)) - } - } - } -} - -/// Creates an iterator from an existing iterator and a stateful function. -/// -/// Specifically, this behaves like `fold`, but yields intermediate results. -/// -/// ## Examples -/// -/// ```gleam -/// // Generate a sequence of partial sums -/// from_list([1, 2, 3, 4, 5]) -/// |> scan(from: 0, with: fn(acc, el) { acc + el }) -/// |> to_list -/// // -> [1, 3, 6, 10, 15] -/// ``` -/// -pub fn scan( - over iterator: Iterator(element), - from initial: acc, - with f: fn(acc, element) -> acc, -) -> Iterator(acc) { - iterator.continuation - |> do_scan(f, initial) - |> Iterator -} - -fn do_zip( - left: fn() -> Action(a), - right: fn() -> Action(b), -) -> fn() -> Action(#(a, b)) { - fn() { - case left() { - Stop -> Stop - Continue(el_left, next_left) -> - case right() { - Stop -> Stop - Continue(el_right, next_right) -> - Continue(#(el_left, el_right), do_zip(next_left, next_right)) - } - } - } -} - -/// Zips two iterators together, emitting values from both -/// until the shorter one runs out. -/// -/// ## Examples -/// -/// ```gleam -/// from_list(["a", "b", "c"]) -/// |> zip(range(20, 30)) -/// |> to_list -/// // -> [#("a", 20), #("b", 21), #("c", 22)] -/// ``` -/// -pub fn zip(left: Iterator(a), right: Iterator(b)) -> Iterator(#(a, b)) { - do_zip(left.continuation, right.continuation) - |> Iterator -} - -// Result of collecting a single chunk by key -type Chunk(element, key) { - AnotherBy(List(element), key, element, fn() -> Action(element)) - LastBy(List(element)) -} - -fn next_chunk( - continuation: fn() -> Action(element), - f: fn(element) -> key, - previous_key: key, - current_chunk: List(element), -) -> Chunk(element, key) { - case continuation() { - Stop -> LastBy(list.reverse(current_chunk)) - Continue(e, next) -> { - let key = f(e) - case key == previous_key { - True -> next_chunk(next, f, key, [e, ..current_chunk]) - False -> AnotherBy(list.reverse(current_chunk), key, e, next) - } - } - } -} - -fn do_chunk( - continuation: fn() -> Action(element), - f: fn(element) -> key, - previous_key: key, - previous_element: element, -) -> Action(List(element)) { - case next_chunk(continuation, f, previous_key, [previous_element]) { - LastBy(chunk) -> Continue(chunk, stop) - AnotherBy(chunk, key, el, next) -> - Continue(chunk, fn() { do_chunk(next, f, key, el) }) - } -} - -/// Creates an iterator that emits chunks of elements -/// for which `f` returns the same value. -/// -/// ## Examples -/// -/// ```gleam -/// from_list([1, 2, 2, 3, 4, 4, 6, 7, 7]) -/// |> chunk(by: fn(n) { n % 2 }) -/// |> to_list -/// // -> [[1], [2, 2], [3], [4, 4, 6], [7, 7]] -/// ``` -/// -pub fn chunk( - over iterator: Iterator(element), - by f: fn(element) -> key, -) -> Iterator(List(element)) { - fn() { - case iterator.continuation() { - Stop -> Stop - Continue(e, next) -> do_chunk(next, f, f(e), e) - } - } - |> Iterator -} - -// Result of collecting a single sized chunk -type SizedChunk(element) { - Another(List(element), fn() -> Action(element)) - Last(List(element)) - NoMore -} - -fn next_sized_chunk( - continuation: fn() -> Action(element), - left: Int, - current_chunk: List(element), -) -> SizedChunk(element) { - case continuation() { - Stop -> - case current_chunk { - [] -> NoMore - remaining -> Last(list.reverse(remaining)) - } - Continue(e, next) -> { - let chunk = [e, ..current_chunk] - case left > 1 { - False -> Another(list.reverse(chunk), next) - True -> next_sized_chunk(next, left - 1, chunk) - } - } - } -} - -fn do_sized_chunk( - continuation: fn() -> Action(element), - count: Int, -) -> fn() -> Action(List(element)) { - fn() { - case next_sized_chunk(continuation, count, []) { - NoMore -> Stop - Last(chunk) -> Continue(chunk, stop) - Another(chunk, next_element) -> - Continue(chunk, do_sized_chunk(next_element, count)) - } - } -} - -/// Creates an iterator that emits chunks of given size. -/// -/// If the last chunk does not have `count` elements, it is yielded -/// as a partial chunk, with less than `count` elements. -/// -/// For any `count` less than 1 this function behaves as if it was set to 1. -/// -/// ## Examples -/// -/// ```gleam -/// from_list([1, 2, 3, 4, 5, 6]) -/// |> sized_chunk(into: 2) -/// |> to_list -/// // -> [[1, 2], [3, 4], [5, 6]] -/// ``` -/// -/// ```gleam -/// from_list([1, 2, 3, 4, 5, 6, 7, 8]) -/// |> sized_chunk(into: 3) -/// |> to_list -/// // -> [[1, 2, 3], [4, 5, 6], [7, 8]] -/// ``` -/// -pub fn sized_chunk( - over iterator: Iterator(element), - into count: Int, -) -> Iterator(List(element)) { - iterator.continuation - |> do_sized_chunk(count) - |> Iterator -} - -fn do_intersperse( - continuation: fn() -> Action(element), - separator: element, -) -> Action(element) { - case continuation() { - Stop -> Stop - Continue(e, next) -> { - let next_interspersed = fn() { do_intersperse(next, separator) } - Continue(separator, fn() { Continue(e, next_interspersed) }) - } - } -} - -/// Creates an iterator that yields the given `elem` element -/// between elements emitted by the underlying iterator. -/// -/// ## Examples -/// -/// ```gleam -/// empty() -/// |> intersperse(with: 0) -/// |> to_list -/// // -> [] -/// ``` -/// -/// ```gleam -/// from_list([1]) -/// |> intersperse(with: 0) -/// |> to_list -/// // -> [1] -/// ``` -/// -/// ```gleam -/// from_list([1, 2, 3, 4, 5]) -/// |> intersperse(with: 0) -/// |> to_list -/// // -> [1, 0, 2, 0, 3, 0, 4, 0, 5] -/// ``` -/// -pub fn intersperse( - over iterator: Iterator(element), - with elem: element, -) -> Iterator(element) { - fn() { - case iterator.continuation() { - Stop -> Stop - Continue(e, next) -> Continue(e, fn() { do_intersperse(next, elem) }) - } - } - |> Iterator -} - -fn do_any( - continuation: fn() -> Action(element), - predicate: fn(element) -> Bool, -) -> Bool { - case continuation() { - Stop -> False - Continue(e, next) -> - case predicate(e) { - True -> True - False -> do_any(next, predicate) - } - } -} - -/// Returns `True` if any element emitted by the iterator satisfies the given predicate, -/// `False` otherwise. -/// -/// This function short-circuits once it finds a satisfying element. -/// -/// An empty iterator results in `False`. -/// -/// ## Examples -/// -/// ```gleam -/// empty() -/// |> any(fn(n) { n % 2 == 0 }) -/// // -> False -/// ``` -/// -/// ```gleam -/// from_list([1, 2, 5, 7, 9]) -/// |> any(fn(n) { n % 2 == 0 }) -/// // -> True -/// ``` -/// -/// ```gleam -/// from_list([1, 3, 5, 7, 9]) -/// |> any(fn(n) { n % 2 == 0 }) -/// // -> False -/// ``` -/// -pub fn any( - in iterator: Iterator(element), - satisfying predicate: fn(element) -> Bool, -) -> Bool { - iterator.continuation - |> do_any(predicate) -} - -fn do_all( - continuation: fn() -> Action(element), - predicate: fn(element) -> Bool, -) -> Bool { - case continuation() { - Stop -> True - Continue(e, next) -> - case predicate(e) { - True -> do_all(next, predicate) - False -> False - } - } -} - -/// Returns `True` if all elements emitted by the iterator satisfy the given predicate, -/// `False` otherwise. -/// -/// This function short-circuits once it finds a non-satisfying element. -/// -/// An empty iterator results in `True`. -/// -/// ## Examples -/// -/// ```gleam -/// empty() -/// |> all(fn(n) { n % 2 == 0 }) -/// // -> True -/// ``` -/// -/// ```gleam -/// from_list([2, 4, 6, 8]) -/// |> all(fn(n) { n % 2 == 0 }) -/// // -> True -/// ``` -/// -/// ```gleam -/// from_list([2, 4, 5, 8]) -/// |> all(fn(n) { n % 2 == 0 }) -/// // -> False -/// ``` -/// -pub fn all( - in iterator: Iterator(element), - satisfying predicate: fn(element) -> Bool, -) -> Bool { - iterator.continuation - |> do_all(predicate) -} - -fn update_group_with(el: element) -> fn(Option(List(element))) -> List(element) { - fn(maybe_group) { - case maybe_group { - Some(group) -> [el, ..group] - None -> [el] - } - } -} - -fn group_updater( - f: fn(element) -> key, -) -> fn(Dict(key, List(element)), element) -> Dict(key, List(element)) { - fn(groups, elem) { - groups - |> dict.upsert(f(elem), update_group_with(elem)) - } -} - -/// Returns a `Dict(k, List(element))` of elements from the given iterator -/// grouped with the given key function. -/// -/// The order within each group is preserved from the iterator. -/// -/// ## Examples -/// -/// ```gleam -/// from_list([1, 2, 3, 4, 5, 6]) -/// |> group(by: fn(n) { n % 3 }) -/// // -> dict.from_list([#(0, [3, 6]), #(1, [1, 4]), #(2, [2, 5])]) -/// ``` -/// -pub fn group( - in iterator: Iterator(element), - by key: fn(element) -> key, -) -> Dict(key, List(element)) { - iterator - |> fold(dict.new(), group_updater(key)) - |> dict.map_values(fn(_, group) { list.reverse(group) }) -} - -/// This function acts similar to fold, but does not take an initial state. -/// Instead, it starts from the first yielded element -/// and combines it with each subsequent element in turn using the given function. -/// The function is called as `f(accumulator, current_element)`. -/// -/// Returns `Ok` to indicate a successful run, and `Error` if called on an empty iterator. -/// -/// ## Examples -/// -/// ```gleam -/// from_list([]) -/// |> reduce(fn(acc, x) { acc + x }) -/// // -> Error(Nil) -/// ``` -/// -/// ```gleam -/// from_list([1, 2, 3, 4, 5]) -/// |> reduce(fn(acc, x) { acc + x }) -/// // -> Ok(15) -/// ``` -/// -pub fn reduce( - over iterator: Iterator(e), - with f: fn(e, e) -> e, -) -> Result(e, Nil) { - case iterator.continuation() { - Stop -> Error(Nil) - Continue(e, next) -> - do_fold(next, f, e) - |> Ok - } -} - -/// Returns the last element in the given iterator. -/// -/// Returns `Error(Nil)` if the iterator is empty. -/// -/// This function runs in linear time. -/// -/// ## Examples -/// -/// ```gleam -/// empty() |> last -/// // -> Error(Nil) -/// ``` -/// -/// ```gleam -/// range(1, 10) |> last -/// // -> Ok(10) -/// ``` -/// -pub fn last(iterator: Iterator(element)) -> Result(element, Nil) { - iterator - |> reduce(fn(_, elem) { elem }) -} - -/// Creates an iterator that yields no elements. -/// -/// ## Examples -/// -/// ```gleam -/// empty() |> to_list -/// // -> [] -/// ``` -/// -pub fn empty() -> Iterator(element) { - Iterator(stop) -} - -/// Creates an iterator that yields exactly one element provided by calling the given function. -/// -/// ## Examples -/// -/// ```gleam -/// once(fn() { 1 }) |> to_list -/// // -> [1] -/// ``` -/// -pub fn once(f: fn() -> element) -> Iterator(element) { - fn() { Continue(f(), stop) } - |> Iterator -} - -/// Creates an iterator that yields the given element exactly once. -/// -/// ## Examples -/// -/// ```gleam -/// single(1) |> to_list -/// // -> [1] -/// ``` -/// -pub fn single(elem: element) -> Iterator(element) { - once(fn() { elem }) -} - -fn do_interleave( - current: fn() -> Action(element), - next: fn() -> Action(element), -) -> Action(element) { - case current() { - Stop -> next() - Continue(e, next_other) -> - Continue(e, fn() { do_interleave(next, next_other) }) - } -} - -/// Creates an iterator that alternates between the two given iterators -/// until both have run out. -/// -/// ## Examples -/// -/// ```gleam -/// from_list([1, 2, 3, 4]) -/// |> interleave(from_list([11, 12, 13, 14])) -/// |> to_list -/// // -> [1, 11, 2, 12, 3, 13, 4, 14] -/// ``` -/// -/// ```gleam -/// from_list([1, 2, 3, 4]) -/// |> interleave(from_list([100])) -/// |> to_list -/// // -> [1, 100, 2, 3, 4] -/// ``` -/// -pub fn interleave( - left: Iterator(element), - with right: Iterator(element), -) -> Iterator(element) { - fn() { do_interleave(left.continuation, right.continuation) } - |> Iterator -} - -fn do_fold_until( - continuation: fn() -> Action(e), - f: fn(acc, e) -> list.ContinueOrStop(acc), - accumulator: acc, -) -> acc { - case continuation() { - Stop -> accumulator - Continue(elem, next) -> - case f(accumulator, elem) { - list.Continue(accumulator) -> do_fold_until(next, f, accumulator) - list.Stop(accumulator) -> accumulator - } - } -} - -/// Like `fold`, `fold_until` reduces an iterator of elements into a single value by calling a given -/// function on each element in turn, but uses `list.ContinueOrStop` to determine -/// whether or not to keep iterating. -/// -/// If called on an iterator of infinite length then this function will only ever -/// return if the function returns `list.Stop`. -/// -/// ## Examples -/// -/// ```gleam -/// import gleam/list -/// -/// let f = fn(acc, e) { -/// case e { -/// _ if e < 4 -> list.Continue(e + acc) -/// _ -> list.Stop(acc) -/// } -/// } -/// -/// from_list([1, 2, 3, 4]) -/// |> fold_until(from: 0, with: f) -/// // -> 6 -/// ``` -/// -pub fn fold_until( - over iterator: Iterator(e), - from initial: acc, - with f: fn(acc, e) -> list.ContinueOrStop(acc), -) -> acc { - iterator.continuation - |> do_fold_until(f, initial) -} - -fn do_try_fold( - over continuation: fn() -> Action(a), - with f: fn(acc, a) -> Result(acc, err), - from accumulator: acc, -) -> Result(acc, err) { - case continuation() { - Stop -> Ok(accumulator) - Continue(elem, next) -> { - case f(accumulator, elem) { - Ok(result) -> do_try_fold(next, f, result) - Error(_) as error -> error - } - } - } -} - -/// A variant of fold that might fail. -/// -/// The folding function should return `Result(accumulator, error)`. -/// If the returned value is `Ok(accumulator)` try_fold will try the next value in the iterator. -/// If the returned value is `Error(error)` try_fold will stop and return that error. -/// -/// ## Examples -/// -/// ```gleam -/// from_list([1, 2, 3, 4]) -/// |> try_fold(0, fn(acc, i) { -/// case i < 3 { -/// True -> Ok(acc + i) -/// False -> Error(Nil) -/// } -/// }) -/// // -> Error(Nil) -/// ``` -/// -pub fn try_fold( - over iterator: Iterator(e), - from initial: acc, - with f: fn(acc, e) -> Result(acc, err), -) -> Result(acc, err) { - iterator.continuation - |> do_try_fold(f, initial) -} - -/// Returns the first element yielded by the given iterator, if it exists, -/// or `Error(Nil)` otherwise. -/// -/// ## Examples -/// -/// ```gleam -/// from_list([1, 2, 3]) |> first -/// // -> Ok(1) -/// ``` -/// -/// ```gleam -/// empty() |> first -/// // -> Error(Nil) -/// ``` -pub fn first(from iterator: Iterator(e)) -> Result(e, Nil) { - case iterator.continuation() { - Stop -> Error(Nil) - Continue(e, _) -> Ok(e) - } -} - -/// Returns nth element yielded by the given iterator, where `0` means the first element. -/// -/// If there are not enough elements in the iterator, `Error(Nil)` is returned. -/// -/// For any `index` less than `0` this function behaves as if it was set to `0`. -/// -/// ## Examples -/// -/// ```gleam -/// from_list([1, 2, 3, 4]) |> at(2) -/// // -> Ok(3) -/// ``` -/// -/// ```gleam -/// from_list([1, 2, 3, 4]) |> at(4) -/// // -> Error(Nil) -/// ``` -/// -/// ```gleam -/// empty() |> at(0) -/// // -> Error(Nil) -/// ``` -/// -pub fn at(in iterator: Iterator(e), get index: Int) -> Result(e, Nil) { - iterator - |> drop(index) - |> first -} - -fn do_length(over continuation: fn() -> Action(e), with length: Int) -> Int { - case continuation() { - Stop -> length - Continue(_, next) -> do_length(next, length + 1) - } -} - -/// Counts the number of elements in the given iterator. -/// -/// This function has to traverse the entire iterator to count its elements, -/// so it runs in linear time. -/// -/// ## Examples -/// -/// ```gleam -/// empty() |> length -/// // -> 0 -/// ``` -/// -/// ```gleam -/// from_list([1, 2, 3, 4]) |> length -/// // -> 4 -/// ``` -/// -pub fn length(over iterator: Iterator(e)) -> Int { - iterator.continuation - |> do_length(0) -} - -/// Traverse an iterator, calling a function on each element. -/// -/// ## Examples -/// -/// ```gleam -/// empty() |> each(io.println) -/// // -> Nil -/// ``` -/// -/// ```gleam -/// from_list(["Tom", "Malory", "Louis"]) |> each(io.println) -/// // -> Nil -/// // Tom -/// // Malory -/// // Louis -/// ``` -/// -pub fn each(over iterator: Iterator(a), with f: fn(a) -> b) -> Nil { - iterator - |> map(f) - |> run -} - -/// Add a new element to the start of an iterator. -/// -/// This function is for use with `use` expressions, to replicate the behaviour -/// of the `yield` keyword found in other languages. -/// -/// ## Examples -/// -/// ```gleam -/// let iterator = { -/// use <- yield(1) -/// use <- yield(2) -/// use <- yield(3) -/// empty() -/// } -/// -/// iterator |> to_list -/// // -> [1, 2, 3] -/// ``` -/// -pub fn yield(element: a, next: fn() -> Iterator(a)) -> Iterator(a) { - Iterator(fn() { Continue(element, fn() { next().continuation() }) }) -} diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam deleted file mode 100644 index c363cda8ffd..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/list.gleam +++ /dev/null @@ -1,2305 +0,0 @@ -//// Lists are an ordered sequence of elements and are one of the most common -//// data types in Gleam. -//// -//// New elements can be added and removed from the front of a list in -//// constant time, while adding and removing from the end requires traversing -//// and copying the whole list, so keep this in mind when designing your -//// programs. -//// -//// There is a dedicated syntax for prefixing to a list: -//// -//// ```gleam -//// let new_list = [1, 2, ..existing_list] -//// ``` -//// -//// And a matching syntax for getting the first elements of a list: -//// -//// ```gleam -//// case list { -//// [first_element, ..rest] -> first_element -//// _ -> "this pattern matches when the list is empty" -//// } -//// ``` -//// - -import gleam/dict.{type Dict} -import gleam/float -import gleam/int -import gleam/order.{type Order} -import gleam/pair - -/// Counts the number of elements in a given list. -/// -/// This function has to traverse the list to determine the number of elements, -/// so it runs in linear time. -/// -/// This function is natively implemented by the virtual machine and is highly -/// optimised. -/// -/// ## Examples -/// -/// ```gleam -/// length([]) -/// // -> 0 -/// ``` -/// -/// ```gleam -/// length([1]) -/// // -> 1 -/// ``` -/// -/// ```gleam -/// length([1, 2]) -/// // -> 2 -/// ``` -/// -@external(erlang, "erlang", "length") -pub fn length(of list: List(a)) -> Int { - count_length(list, 0) -} - -fn count_length(list: List(a), count: Int) -> Int { - case list { - [_, ..list] -> count_length(list, count + 1) - _ -> count - } -} - -/// Counts the number of elements in a given list satisfying a given predicate. -/// -/// This function has to traverse the list to determine the number of elements, -/// so it runs in linear time. -/// -/// ## Examples -/// -/// ```gleam -/// count([], fn(a) { a > 0 }) -/// // -> 0 -/// ``` -/// -/// ```gleam -/// count([1], fn(a) { a > 0 }) -/// // -> 1 -/// ``` -/// -/// ```gleam -/// count([1, 2, 3], int.is_odd) -/// // -> 2 -/// ``` -/// -pub fn count(list: List(a), where predicate: fn(a) -> Bool) -> Int { - fold(list, 0, fn(acc, value) { - case predicate(value) { - True -> acc + 1 - False -> acc - } - }) -} - -/// Creates a new list from a given list containing the same elements but in the -/// opposite order. -/// -/// This function has to traverse the list to create the new reversed list, so -/// it runs in linear time. -/// -/// This function is natively implemented by the virtual machine and is highly -/// optimised. -/// -/// ## Examples -/// -/// ```gleam -/// reverse([]) -/// // -> [] -/// ``` -/// -/// ```gleam -/// reverse([1]) -/// // -> [1] -/// ``` -/// -/// ```gleam -/// reverse([1, 2]) -/// // -> [2, 1] -/// ``` -/// -@external(erlang, "lists", "reverse") -pub fn reverse(list: List(a)) -> List(a) { - do_reverse(list, []) -} - -fn do_reverse(remaining: List(a), accumulator: List(a)) -> List(a) { - case remaining { - [] -> accumulator - [item, ..rest] -> do_reverse(rest, [item, ..accumulator]) - } -} - -/// Determines whether or not the list is empty. -/// -/// This function runs in constant time. -/// -/// ## Examples -/// -/// ```gleam -/// is_empty([]) -/// // -> True -/// ``` -/// -/// ```gleam -/// is_empty([1]) -/// // -> False -/// ``` -/// -/// ```gleam -/// is_empty([1, 1]) -/// // -> False -/// ``` -/// -pub fn is_empty(list: List(a)) -> Bool { - list == [] -} - -/// Determines whether or not a given element exists within a given list. -/// -/// This function traverses the list to find the element, so it runs in linear -/// time. -/// -/// ## Examples -/// -/// ```gleam -/// [] |> contains(any: 0) -/// // -> False -/// ``` -/// -/// ```gleam -/// [0] |> contains(any: 0) -/// // -> True -/// ``` -/// -/// ```gleam -/// [1] |> contains(any: 0) -/// // -> False -/// ``` -/// -/// ```gleam -/// [1, 1] |> contains(any: 0) -/// // -> False -/// ``` -/// -/// ```gleam -/// [1, 0] |> contains(any: 0) -/// // -> True -/// ``` -/// -pub fn contains(list: List(a), any elem: a) -> Bool { - case list { - [] -> False - [first, ..] if first == elem -> True - [_, ..rest] -> contains(rest, elem) - } -} - -/// Gets the first element from the start of the list, if there is one. -/// -/// ## Examples -/// -/// ```gleam -/// first([]) -/// // -> Error(Nil) -/// ``` -/// -/// ```gleam -/// first([0]) -/// // -> Ok(0) -/// ``` -/// -/// ```gleam -/// first([1, 2]) -/// // -> Ok(1) -/// ``` -/// -pub fn first(list: List(a)) -> Result(a, Nil) { - case list { - [] -> Error(Nil) - [x, ..] -> Ok(x) - } -} - -/// Returns the list minus the first element. If the list is empty, `Error(Nil)` is -/// returned. -/// -/// This function runs in constant time and does not make a copy of the list. -/// -/// ## Examples -/// -/// ```gleam -/// rest([]) -/// // -> Error(Nil) -/// ``` -/// -/// ```gleam -/// rest([0]) -/// // -> Ok([]) -/// ``` -/// -/// ```gleam -/// rest([1, 2]) -/// // -> Ok([2]) -/// ``` -/// -pub fn rest(list: List(a)) -> Result(List(a), Nil) { - case list { - [] -> Error(Nil) - [_, ..rest] -> Ok(rest) - } -} - -fn update_group(f: fn(a) -> k) -> fn(Dict(k, List(a)), a) -> Dict(k, List(a)) { - fn(groups, elem) { - case dict.get(groups, f(elem)) { - Ok(existing) -> dict.insert(groups, f(elem), [elem, ..existing]) - Error(_) -> dict.insert(groups, f(elem), [elem]) - } - } -} - -/// Takes a list and groups the values by a key -/// which is built from a key function. -/// -/// Does not preserve the initial value order. -/// -/// ## Examples -/// -/// ```gleam -/// import gleam/dict -/// -/// [Ok(3), Error("Wrong"), Ok(200), Ok(73)] -/// |> group(by: fn(i) { -/// case i { -/// Ok(_) -> "Successful" -/// Error(_) -> "Failed" -/// } -/// }) -/// |> dict.to_list -/// // -> [ -/// // #("Failed", [Error("Wrong")]), -/// // #("Successful", [Ok(73), Ok(200), Ok(3)]) -/// // ] -/// ``` -/// -/// ```gleam -/// import gleam/dict -/// -/// group([1,2,3,4,5], by: fn(i) { i - i / 3 * 3 }) -/// |> dict.to_list -/// // -> [#(0, [3]), #(1, [4, 1]), #(2, [5, 2])] -/// ``` -/// -pub fn group(list: List(v), by key: fn(v) -> k) -> Dict(k, List(v)) { - fold(list, dict.new(), update_group(key)) -} - -fn do_filter(list: List(a), fun: fn(a) -> Bool, acc: List(a)) -> List(a) { - case list { - [] -> reverse(acc) - [first, ..rest] -> { - let new_acc = case fun(first) { - True -> [first, ..acc] - False -> acc - } - do_filter(rest, fun, new_acc) - } - } -} - -/// Returns a new list containing only the elements from the first list for -/// which the given functions returns `True`. -/// -/// ## Examples -/// -/// ```gleam -/// filter([2, 4, 6, 1], fn(x) { x > 2 }) -/// // -> [4, 6] -/// ``` -/// -/// ```gleam -/// filter([2, 4, 6, 1], fn(x) { x > 6 }) -/// // -> [] -/// ``` -/// -pub fn filter(list: List(a), keeping predicate: fn(a) -> Bool) -> List(a) { - do_filter(list, predicate, []) -} - -fn do_filter_map( - list: List(a), - fun: fn(a) -> Result(b, e), - acc: List(b), -) -> List(b) { - case list { - [] -> reverse(acc) - [first, ..rest] -> { - let new_acc = case fun(first) { - Ok(first) -> [first, ..acc] - Error(_) -> acc - } - do_filter_map(rest, fun, new_acc) - } - } -} - -/// Returns a new list containing only the elements from the first list for -/// which the given functions returns `Ok(_)`. -/// -/// ## Examples -/// -/// ```gleam -/// filter_map([2, 4, 6, 1], Error) -/// // -> [] -/// ``` -/// -/// ```gleam -/// filter_map([2, 4, 6, 1], fn(x) { Ok(x + 1) }) -/// // -> [3, 5, 7, 2] -/// ``` -/// -pub fn filter_map(list: List(a), with fun: fn(a) -> Result(b, e)) -> List(b) { - do_filter_map(list, fun, []) -} - -fn do_map(list: List(a), fun: fn(a) -> b, acc: List(b)) -> List(b) { - case list { - [] -> reverse(acc) - [first, ..rest] -> do_map(rest, fun, [fun(first), ..acc]) - } -} - -/// Returns a new list containing only the elements of the first list after the -/// function has been applied to each one. -/// -/// ## Examples -/// -/// ```gleam -/// map([2, 4, 6], fn(x) { x * 2 }) -/// // -> [4, 8, 12] -/// ``` -/// -pub fn map(list: List(a), with fun: fn(a) -> b) -> List(b) { - do_map(list, fun, []) -} - -/// Combines two lists into a single list using the given function. -/// -/// If a list is longer than the other the extra elements are dropped. -/// -/// ## Examples -/// -/// ```gleam -/// map2([1, 2, 3], [4, 5, 6], fn(x, y) { x + y }) -/// // -> [5, 7, 9] -/// ``` -/// -/// ```gleam -/// map2([1, 2], ["a", "b", "c"], fn(i, x) { #(i, x) }) -/// // -> [#(1, "a"), #(2, "b")] -/// ``` -/// -pub fn map2(list1: List(a), list2: List(b), with fun: fn(a, b) -> c) -> List(c) { - do_map2(list1, list2, fun, []) -} - -fn do_map2( - list1: List(a), - list2: List(b), - fun: fn(a, b) -> c, - acc: List(c), -) -> List(c) { - case list1, list2 { - [], _ | _, [] -> reverse(acc) - [a, ..as_], [b, ..bs] -> do_map2(as_, bs, fun, [fun(a, b), ..acc]) - } -} - -/// Similar to `map` but also lets you pass around an accumulated value. -/// -/// ## Examples -/// -/// ```gleam -/// map_fold( -/// over: [1, 2, 3], -/// from: 100, -/// with: fn(memo, i) { #(memo + i, i * 2) } -/// ) -/// // -> #(106, [2, 4, 6]) -/// ``` -/// -pub fn map_fold( - over list: List(a), - from initial: acc, - with fun: fn(acc, a) -> #(acc, b), -) -> #(acc, List(b)) { - fold(over: list, from: #(initial, []), with: fn(acc, item) { - let #(current_acc, items) = acc - let #(next_acc, next_item) = fun(current_acc, item) - #(next_acc, [next_item, ..items]) - }) - |> pair.map_second(reverse) -} - -fn do_index_map( - list: List(a), - fun: fn(a, Int) -> b, - index: Int, - acc: List(b), -) -> List(b) { - case list { - [] -> reverse(acc) - [first, ..rest] -> { - let acc = [fun(first, index), ..acc] - do_index_map(rest, fun, index + 1, acc) - } - } -} - -/// Returns a new list containing only the elements of the first list after the -/// function has been applied to each one and their index. -/// -/// The index starts at 0, so the first element is 0, the second is 1, and so -/// on. -/// -/// ## Examples -/// -/// ```gleam -/// index_map(["a", "b"], fn(x, i) { #(i, x) }) -/// // -> [#(0, "a"), #(1, "b")] -/// ``` -/// -pub fn index_map(list: List(a), with fun: fn(a, Int) -> b) -> List(b) { - do_index_map(list, fun, 0, []) -} - -fn do_try_map( - list: List(a), - fun: fn(a) -> Result(b, e), - acc: List(b), -) -> Result(List(b), e) { - case list { - [] -> Ok(reverse(acc)) - [first, ..rest] -> - case fun(first) { - Ok(first) -> do_try_map(rest, fun, [first, ..acc]) - Error(error) -> Error(error) - } - } -} - -/// Takes a function that returns a `Result` and applies it to each element in a -/// given list in turn. -/// -/// If the function returns `Ok(new_value)` for all elements in the list then a -/// list of the new values is returned. -/// -/// If the function returns `Error(reason)` for any of the elements then it is -/// returned immediately. None of the elements in the list are processed after -/// one returns an `Error`. -/// -/// ## Examples -/// -/// ```gleam -/// try_map([1, 2, 3], fn(x) { Ok(x + 2) }) -/// // -> Ok([3, 4, 5]) -/// ``` -/// -/// ```gleam -/// try_map([1, 2, 3], fn(_) { Error(0) }) -/// // -> Error(0) -/// ``` -/// -/// ```gleam -/// try_map([[1], [2, 3]], first) -/// // -> Ok([1, 2]) -/// ``` -/// -/// ```gleam -/// try_map([[1], [], [2]], first) -/// // -> Error(Nil) -/// ``` -/// -pub fn try_map( - over list: List(a), - with fun: fn(a) -> Result(b, e), -) -> Result(List(b), e) { - do_try_map(list, fun, []) -} - -/// Returns a list that is the given list with up to the given number of -/// elements removed from the front of the list. -/// -/// If the element has less than the number of elements an empty list is -/// returned. -/// -/// This function runs in linear time but does not copy the list. -/// -/// ## Examples -/// -/// ```gleam -/// drop([1, 2, 3, 4], 2) -/// // -> [3, 4] -/// ``` -/// -/// ```gleam -/// drop([1, 2, 3, 4], 9) -/// // -> [] -/// ``` -/// -pub fn drop(from list: List(a), up_to n: Int) -> List(a) { - case n <= 0 { - True -> list - False -> - case list { - [] -> [] - [_, ..rest] -> drop(rest, n - 1) - } - } -} - -fn do_take(list: List(a), n: Int, acc: List(a)) -> List(a) { - case n <= 0 { - True -> reverse(acc) - False -> - case list { - [] -> reverse(acc) - [first, ..rest] -> do_take(rest, n - 1, [first, ..acc]) - } - } -} - -/// Returns a list containing the first given number of elements from the given -/// list. -/// -/// If the element has less than the number of elements then the full list is -/// returned. -/// -/// This function runs in linear time. -/// -/// ## Examples -/// -/// ```gleam -/// take([1, 2, 3, 4], 2) -/// // -> [1, 2] -/// ``` -/// -/// ```gleam -/// take([1, 2, 3, 4], 9) -/// // -> [1, 2, 3, 4] -/// ``` -/// -pub fn take(from list: List(a), up_to n: Int) -> List(a) { - do_take(list, n, []) -} - -/// Returns a new empty list. -/// -/// ## Examples -/// -/// ```gleam -/// new() -/// // -> [] -/// ``` -/// -pub fn new() -> List(a) { - [] -} - -/// Returns the given item wrapped in a list. -/// -/// ## Examples -/// -/// ```gleam -/// wrap(1) -/// // -> [1] -/// -/// wrap(["a", "b", "c"]) -/// // -> [["a", "b", "c"]] -/// -/// wrap([[]]) -/// // -> [[[]]] -/// ``` -/// -/// -pub fn wrap(item: a) -> List(a) { - [item] -} - -/// Joins one list onto the end of another. -/// -/// This function runs in linear time, and it traverses and copies the first -/// list. -/// -/// ## Examples -/// -/// ```gleam -/// append([1, 2], [3]) -/// // -> [1, 2, 3] -/// ``` -/// -@external(erlang, "lists", "append") -pub fn append(first: List(a), second: List(a)) -> List(a) { - do_append(reverse(first), second) -} - -fn do_append(first: List(a), second: List(a)) -> List(a) { - case first { - [] -> second - [item, ..rest] -> do_append(rest, [item, ..second]) - } -} - -/// Prefixes an item to a list. This can also be done using the dedicated -/// syntax instead -/// -/// ```gleam -/// let existing_list = [2, 3, 4] -/// -/// [1, ..existing_list] -/// // -> [1, 2, 3, 4] -/// -/// prepend(to: existing_list, this: 1) -/// // -> [1, 2, 3, 4] -/// ``` -/// -pub fn prepend(to list: List(a), this item: a) -> List(a) { - [item, ..list] -} - -// Reverses a list and prepends it to another list -fn reverse_and_prepend(list prefix: List(a), to suffix: List(a)) -> List(a) { - case prefix { - [] -> suffix - [first, ..rest] -> reverse_and_prepend(list: rest, to: [first, ..suffix]) - } -} - -fn do_concat(lists: List(List(a)), acc: List(a)) -> List(a) { - case lists { - [] -> reverse(acc) - [list, ..further_lists] -> - do_concat(further_lists, reverse_and_prepend(list: list, to: acc)) - } -} - -/// Joins a list of lists into a single list. -/// -/// This function traverses all elements twice. -/// -/// ## Examples -/// -/// ```gleam -/// concat([[1], [2, 3], []]) -/// // -> [1, 2, 3] -/// ``` -/// -@deprecated("Use `list.flatten` instead.") -pub fn concat(lists: List(List(a))) -> List(a) { - do_concat(lists, []) -} - -/// This is the same as `concat`: it joins a list of lists into a single -/// list. -/// -/// This function traverses all elements twice. -/// -/// ## Examples -/// -/// ```gleam -/// flatten([[1], [2, 3], []]) -/// // -> [1, 2, 3] -/// ``` -/// -pub fn flatten(lists: List(List(a))) -> List(a) { - do_concat(lists, []) -} - -/// Maps the list with the given function into a list of lists, and then flattens it. -/// -/// ## Examples -/// -/// ```gleam -/// flat_map([2, 4, 6], fn(x) { [x, x + 1] }) -/// // -> [2, 3, 4, 5, 6, 7] -/// ``` -/// -pub fn flat_map(over list: List(a), with fun: fn(a) -> List(b)) -> List(b) { - map(list, fun) - |> flatten -} - -/// Reduces a list of elements into a single value by calling a given function -/// on each element, going from left to right. -/// -/// `fold([1, 2, 3], 0, add)` is the equivalent of -/// `add(add(add(0, 1), 2), 3)`. -/// -/// This function runs in linear time. -/// -pub fn fold( - over list: List(a), - from initial: acc, - with fun: fn(acc, a) -> acc, -) -> acc { - case list { - [] -> initial - [x, ..rest] -> fold(rest, fun(initial, x), fun) - } -} - -/// Reduces a list of elements into a single value by calling a given function -/// on each element, going from right to left. -/// -/// `fold_right([1, 2, 3], 0, add)` is the equivalent of -/// `add(add(add(0, 3), 2), 1)`. -/// -/// This function runs in linear time. -/// -/// Unlike `fold` this function is not tail recursive. Where possible use -/// `fold` instead as it will use less memory. -/// -pub fn fold_right( - over list: List(a), - from initial: acc, - with fun: fn(acc, a) -> acc, -) -> acc { - case list { - [] -> initial - [x, ..rest] -> fun(fold_right(rest, initial, fun), x) - } -} - -fn do_index_fold( - over: List(a), - acc: acc, - with: fn(acc, a, Int) -> acc, - index: Int, -) -> acc { - case over { - [] -> acc - [first, ..rest] -> - do_index_fold(rest, with(acc, first, index), with, index + 1) - } -} - -/// Like fold but the folding function also receives the index of the current element. -/// -/// ## Examples -/// -/// ```gleam -/// ["a", "b", "c"] -/// |> index_fold([], fn(acc, item, index) { ... }) -/// ``` -/// -pub fn index_fold( - over list: List(a), - from initial: acc, - with fun: fn(acc, a, Int) -> acc, -) -> acc { - do_index_fold(list, initial, fun, 0) -} - -/// A variant of fold that might fail. -/// -/// The folding function should return `Result(accumulator, error)`. -/// If the returned value is `Ok(accumulator)` try_fold will try the next value in the list. -/// If the returned value is `Error(error)` try_fold will stop and return that error. -/// -/// ## Examples -/// -/// ```gleam -/// [1, 2, 3, 4] -/// |> try_fold(0, fn(acc, i) { -/// case i < 3 { -/// True -> Ok(acc + i) -/// False -> Error(Nil) -/// } -/// }) -/// // -> Error(Nil) -/// ``` -/// -pub fn try_fold( - over list: List(a), - from initial: acc, - with fun: fn(acc, a) -> Result(acc, e), -) -> Result(acc, e) { - case list { - [] -> Ok(initial) - [first, ..rest] -> - case fun(initial, first) { - Ok(result) -> try_fold(rest, result, fun) - Error(_) as error -> error - } - } -} - -pub type ContinueOrStop(a) { - Continue(a) - Stop(a) -} - -/// A variant of fold that allows to stop folding earlier. -/// -/// The folding function should return `ContinueOrStop(accumulator)`. -/// If the returned value is `Continue(accumulator)` fold_until will try the next value in the list. -/// If the returned value is `Stop(accumulator)` fold_until will stop and return that accumulator. -/// -/// ## Examples -/// -/// ```gleam -/// [1, 2, 3, 4] -/// |> fold_until(0, fn(acc, i) { -/// case i < 3 { -/// True -> Continue(acc + i) -/// False -> Stop(acc) -/// } -/// }) -/// // -> 3 -/// ``` -/// -pub fn fold_until( - over list: List(a), - from initial: acc, - with fun: fn(acc, a) -> ContinueOrStop(acc), -) -> acc { - case list { - [] -> initial - [first, ..rest] -> - case fun(initial, first) { - Continue(next_accumulator) -> fold_until(rest, next_accumulator, fun) - Stop(b) -> b - } - } -} - -/// Finds the first element in a given list for which the given function returns -/// `True`. -/// -/// Returns `Error(Nil)` if no such element is found. -/// -/// ## Examples -/// -/// ```gleam -/// find([1, 2, 3], fn(x) { x > 2 }) -/// // -> Ok(3) -/// ``` -/// -/// ```gleam -/// find([1, 2, 3], fn(x) { x > 4 }) -/// // -> Error(Nil) -/// ``` -/// -/// ```gleam -/// find([], fn(_) { True }) -/// // -> Error(Nil) -/// ``` -/// -pub fn find( - in list: List(a), - one_that is_desired: fn(a) -> Bool, -) -> Result(a, Nil) { - case list { - [] -> Error(Nil) - [x, ..rest] -> - case is_desired(x) { - True -> Ok(x) - _ -> find(in: rest, one_that: is_desired) - } - } -} - -/// Finds the first element in a given list for which the given function returns -/// `Ok(new_value)`, then returns the wrapped `new_value`. -/// -/// Returns `Error(Nil)` if no such element is found. -/// -/// ## Examples -/// -/// ```gleam -/// find_map([[], [2], [3]], first) -/// // -> Ok(2) -/// ``` -/// -/// ```gleam -/// find_map([[], []], first) -/// // -> Error(Nil) -/// ``` -/// -/// ```gleam -/// find_map([], first) -/// // -> Error(Nil) -/// ``` -/// -pub fn find_map( - in list: List(a), - with fun: fn(a) -> Result(b, c), -) -> Result(b, Nil) { - case list { - [] -> Error(Nil) - [x, ..rest] -> - case fun(x) { - Ok(x) -> Ok(x) - _ -> find_map(in: rest, with: fun) - } - } -} - -/// Returns `True` if the given function returns `True` for all the elements in -/// the given list. If the function returns `False` for any of the elements it -/// immediately returns `False` without checking the rest of the list. -/// -/// ## Examples -/// -/// ```gleam -/// all([], fn(x) { x > 3 }) -/// // -> True -/// ``` -/// -/// ```gleam -/// all([4, 5], fn(x) { x > 3 }) -/// // -> True -/// ``` -/// -/// ```gleam -/// all([4, 3], fn(x) { x > 3 }) -/// // -> False -/// ``` -/// -pub fn all(in list: List(a), satisfying predicate: fn(a) -> Bool) -> Bool { - case list { - [] -> True - [first, ..rest] -> - case predicate(first) { - True -> all(rest, predicate) - False -> False - } - } -} - -/// Returns `True` if the given function returns `True` for any the elements in -/// the given list. If the function returns `True` for any of the elements it -/// immediately returns `True` without checking the rest of the list. -/// -/// ## Examples -/// -/// ```gleam -/// any([], fn(x) { x > 3 }) -/// // -> False -/// ``` -/// -/// ```gleam -/// any([4, 5], fn(x) { x > 3 }) -/// // -> True -/// ``` -/// -/// ```gleam -/// any([4, 3], fn(x) { x > 4 }) -/// // -> False -/// ``` -/// -/// ```gleam -/// any([3, 4], fn(x) { x > 3 }) -/// // -> True -/// ``` -/// -pub fn any(in list: List(a), satisfying predicate: fn(a) -> Bool) -> Bool { - case list { - [] -> False - [first, ..rest] -> - case predicate(first) { - True -> True - False -> any(rest, predicate) - } - } -} - -fn do_zip(one: List(a), other: List(b), acc: List(#(a, b))) -> List(#(a, b)) { - case one, other { - [first_one, ..rest_one], [first_other, ..rest_other] -> - do_zip(rest_one, rest_other, [#(first_one, first_other), ..acc]) - _, _ -> reverse(acc) - } -} - -/// Takes two lists and returns a single list of 2-element tuples. -/// -/// If one of the lists is longer than the other, the remaining elements from -/// the longer list are not used. -/// -/// ## Examples -/// -/// ```gleam -/// zip([], []) -/// // -> [] -/// ``` -/// -/// ```gleam -/// zip([1, 2], [3]) -/// // -> [#(1, 3)] -/// ``` -/// -/// ```gleam -/// zip([1], [3, 4]) -/// // -> [#(1, 3)] -/// ``` -/// -/// ```gleam -/// zip([1, 2], [3, 4]) -/// // -> [#(1, 3), #(2, 4)] -/// ``` -/// -pub fn zip(list: List(a), with other: List(b)) -> List(#(a, b)) { - do_zip(list, other, []) -} - -/// Takes two lists and returns a single list of 2-element tuples. -/// -/// If one of the lists is longer than the other, an `Error` is returned. -/// -/// ## Examples -/// -/// ```gleam -/// strict_zip([], []) -/// // -> Ok([]) -/// ``` -/// -/// ```gleam -/// strict_zip([1, 2], [3]) -/// // -> Error(Nil) -/// ``` -/// -/// ```gleam -/// strict_zip([1], [3, 4]) -/// // -> Error(Nil) -/// ``` -/// -/// ```gleam -/// strict_zip([1, 2], [3, 4]) -/// // -> Ok([#(1, 3), #(2, 4)]) -/// ``` -/// -pub fn strict_zip( - list: List(a), - with other: List(b), -) -> Result(List(#(a, b)), Nil) { - case length(of: list) == length(of: other) { - True -> Ok(zip(list, other)) - False -> Error(Nil) - } -} - -fn do_unzip( - input: List(#(a, b)), - one: List(a), - other: List(b), -) -> #(List(a), List(b)) { - case input { - [] -> #(reverse(one), reverse(other)) - [#(first_one, first_other), ..rest] -> - do_unzip(rest, [first_one, ..one], [first_other, ..other]) - } -} - -/// Takes a single list of 2-element tuples and returns two lists. -/// -/// ## Examples -/// -/// ```gleam -/// unzip([#(1, 2), #(3, 4)]) -/// // -> #([1, 3], [2, 4]) -/// ``` -/// -/// ```gleam -/// unzip([]) -/// // -> #([], []) -/// ``` -/// -pub fn unzip(input: List(#(a, b))) -> #(List(a), List(b)) { - do_unzip(input, [], []) -} - -fn do_intersperse(list: List(a), separator: a, acc: List(a)) -> List(a) { - case list { - [] -> reverse(acc) - [x, ..rest] -> do_intersperse(rest, separator, [x, separator, ..acc]) - } -} - -/// Inserts a given value between each existing element in a given list. -/// -/// This function runs in linear time and copies the list. -/// -/// ## Examples -/// -/// ```gleam -/// intersperse([1, 1, 1], 2) -/// // -> [1, 2, 1, 2, 1] -/// ``` -/// -/// ```gleam -/// intersperse([], 2) -/// // -> [] -/// ``` -/// -pub fn intersperse(list: List(a), with elem: a) -> List(a) { - case list { - [] | [_] -> list - [x, ..rest] -> do_intersperse(rest, elem, [x]) - } -} - -/// Removes any duplicate elements from a given list. -/// -/// This function returns in loglinear time. -/// -/// ## Examples -/// -/// ```gleam -/// unique([1, 1, 1, 4, 7, 3, 3, 4]) -/// // -> [1, 4, 7, 3] -/// ``` -/// -pub fn unique(list: List(a)) -> List(a) { - case list { - [] -> [] - [x, ..rest] -> [x, ..unique(filter(rest, fn(y) { y != x }))] - } -} - -/// Sorts from smallest to largest based upon the ordering specified by a given -/// function. -/// -/// ## Examples -/// -/// ```gleam -/// import gleam/int -/// -/// sort([4, 3, 6, 5, 4, 1, 2], by: int.compare) -/// // -> [1, 2, 3, 4, 4, 5, 6] -/// ``` -/// -pub fn sort(list: List(a), by compare: fn(a, a) -> Order) -> List(a) { - // This is a natural, tail recursive, stable merge sort: - // - natural: it is very efficient if you call it on a list that is already - // (pre)sorted because it works on slices of the original list. - // - tail recursive: the stack won't grow linearly with the size of the list. - // - stable: if two items are considered to be equal then their original - // relative order is preserved. - case list { - // If the list has zero/one item then it's already sorted. - [] -> [] - [x] -> [x] - - // Otherwise the algorithm works as follow: we split the list in sequences - // of already sorted values as they appear in the list and then we merge - // those together two by two using `merge_all`. - [x, y, ..rest] -> { - // We need to compare the first two items to properly call `sequences` - // with the correct initial values. If the second item is <= than the - // first, then we know we'll start by growing a descending sequence - // (and an ascending one in the opposite case). - let direction = case compare(x, y) { - order.Lt | order.Eq -> Ascending - order.Gt -> Descending - } - - // `sequences` produces sequences in ascending order so we call the - // `merge_all` function saying it to expect all sequences to be sorted - // that way. - let sequences = sequences(rest, compare, [x], direction, y, []) - merge_all(sequences, Ascending, compare) - } - } -} - -type Sorting { - Ascending - Descending -} - -/// Given a list it returns slices of it that are locally sorted in ascending -/// order. -/// -/// Imagine you have this list: -/// -/// ``` -/// [1, 2, 3, 2, 1, 0] -/// ^^^^^^^ ^^^^^^^ This is a slice in descending order -/// | -/// | This is a slice that is sorted in ascending order -/// ``` -/// -/// So the produced result will contain these two slices, each one sorted in -/// ascending order: `[[1, 2, 3], [0, 1, 2]]`. -/// -/// - `growing` is an accumulator with the current slice being grown -/// - `direction` is the growing direction of the slice being grown, it could -/// either be ascending or strictly descending -/// - `prev` is the previous element that needs to be added to the growing slice -/// it is carried around to check whether we have to keep growing the current -/// slice or not -/// - `acc` is the accumulator containing the slices sorted in ascending order -/// -fn sequences( - list: List(a), - compare: fn(a, a) -> Order, - growing: List(a), - direction: Sorting, - prev: a, - acc: List(List(a)), -) -> List(List(a)) { - // First of all we must not forget to add the previous element to the - // currently growing slice. - let growing = [prev, ..growing] - - case list { - [] -> - case direction { - // Notice how we have to reverse the accumulator we're growing: since - // we always add items to the head, `growing` is built in the opposite - // sorting order of what it actually is in the original list. - Ascending -> [do_reverse(growing, []), ..acc] - Descending -> [growing, ..acc] - } - - [new, ..rest] -> - case compare(prev, new), direction { - // In case the new element respects the ordering of the growing - // sequence, then we just keep growing it. - // Notice how a growing sequence is weakly growing (that is it can have - // consecutive equal items) while a decreasing sequence is strictly - // decreasing (no consecutive equal items), this is needed to make the - // algorithm stable! - order.Gt, Descending | order.Lt, Ascending | order.Eq, Ascending -> - sequences(rest, compare, growing, direction, new, acc) - - // We were growing an ascending (descending) sequence and the new item - // is smaller (bigger) than the previous one, this means we have to stop - // growing this sequence and start with a new one whose first item will - // be the one we just found. - order.Gt, Ascending | order.Lt, Descending | order.Eq, Descending -> { - let acc = case direction { - Ascending -> [do_reverse(growing, []), ..acc] - Descending -> [growing, ..acc] - } - case rest { - // The list is over so we just create a sequence containing the last - // item we saw and add it to the accumulator before returning it. - [] -> [[new], ..acc] - - // If the list is not over we have a peek at the next item to decide - // in which direction is growing the new sequence and make the - // recursive call with the appropriate arguments. - [next, ..rest] -> { - let direction = case compare(new, next) { - order.Lt | order.Eq -> Ascending - order.Gt -> Descending - } - sequences(rest, compare, [new], direction, next, acc) - } - } - } - } - } -} - -/// Given some some sorted sequences (assumed to be sorted in `direction`) it -/// merges them all together until we're left with just a list sorted in -/// ascending order. -/// -fn merge_all( - sequences: List(List(a)), - direction: Sorting, - compare: fn(a, a) -> Order, -) -> List(a) { - case sequences, direction { - [], _ -> [] - - // If we have a single list in ascending order then we're done. - [sequence], Ascending -> sequence - - // If we have a single list in descending order, we reverse it to make sure - // it's in ascending order and we're done. - [sequence], Descending -> do_reverse(sequence, []) - - // Merging together sequences that are in ascending (descending) order - // reverses their order, so the recursive call will assume to be merging - // lists sorted in the opposite order! - _, Ascending -> { - let sequences = merge_ascending_pairs(sequences, compare, []) - merge_all(sequences, Descending, compare) - } - - _, Descending -> { - let sequences = merge_descending_pairs(sequences, compare, []) - merge_all(sequences, Ascending, compare) - } - } -} - -/// Given a list of ascending lists, it merges adjacent pairs into a single -/// descending list, halving their number. -/// It returns a list of the remaining descending lists. -/// -fn merge_ascending_pairs( - sequences: List(List(a)), - compare: fn(a, a) -> Order, - acc: List(List(a)), -) { - case sequences { - [] -> do_reverse(acc, []) - - // Beware, if we have just one item left we must reverse it: we take - // ascending lists as input and have to return descending ones. - // If we returned it like it is it would be sorted in ascending order. - [sequence] -> do_reverse([do_reverse(sequence, []), ..acc], []) - - [ascending1, ascending2, ..rest] -> { - let descending = merge_ascendings(ascending1, ascending2, compare, []) - merge_ascending_pairs(rest, compare, [descending, ..acc]) - } - } -} - -/// This is the same as merge_ascending_pairs but flipped for descending lists. -/// -fn merge_descending_pairs( - sequences: List(List(a)), - compare: fn(a, a) -> Order, - acc: List(List(a)), -) { - case sequences { - [] -> do_reverse(acc, []) - - [sequence] -> do_reverse([do_reverse(sequence, []), ..acc], []) - - [descending1, descending2, ..rest] -> { - let ascending = merge_descendings(descending1, descending2, compare, []) - merge_descending_pairs(rest, compare, [ascending, ..acc]) - } - } -} - -/// Merges two lists sorted in ascending order into a single list sorted in -/// descending order according to the given comparator function. -/// -/// This reversing of the sort order is not avoidable if we want to implement -/// merge as a tail recursive function. We could reverse the accumulator before -/// returning it but that would end up being less efficient; so the merging -/// algorithm has to play around this. -/// -fn merge_ascendings( - list1: List(a), - list2: List(a), - compare: fn(a, a) -> Order, - acc: List(a), -) -> List(a) { - case list1, list2 { - [], list | list, [] -> do_reverse(list, acc) - - [first1, ..rest1], [first2, ..rest2] -> - case compare(first1, first2) { - order.Lt -> merge_ascendings(rest1, list2, compare, [first1, ..acc]) - order.Gt | order.Eq -> - merge_ascendings(list1, rest2, compare, [first2, ..acc]) - } - } -} - -/// This is exactly the same as merge_ascendings but mirrored: it merges two -/// lists sorted in descending order into a single list sorted in ascending -/// order according to the given comparator function. -/// -/// This reversing of the sort order is not avoidable if we want to implement -/// merge as a tail recursive function. We could reverse the accumulator before -/// returning it but that would end up being less efficient; so the merging -/// algorithm has to play around this. -/// -fn merge_descendings( - list1: List(a), - list2: List(a), - compare: fn(a, a) -> Order, - acc: List(a), -) -> List(a) { - case list1, list2 { - [], list | list, [] -> do_reverse(list, acc) - [first1, ..rest1], [first2, ..rest2] -> - case compare(first1, first2) { - order.Lt -> merge_descendings(list1, rest2, compare, [first2, ..acc]) - order.Gt | order.Eq -> - merge_descendings(rest1, list2, compare, [first1, ..acc]) - } - } -} - -/// Creates a list of ints ranging from a given start and finish. -/// -/// ## Examples -/// -/// ```gleam -/// range(0, 0) -/// // -> [0] -/// ``` -/// -/// ```gleam -/// range(0, 5) -/// // -> [0, 1, 2, 3, 4, 5] -/// ``` -/// -/// ```gleam -/// range(1, -5) -/// // -> [1, 0, -1, -2, -3, -4, -5] -/// ``` -/// -pub fn range(from start: Int, to stop: Int) -> List(Int) { - tail_recursive_range(start, stop, []) -} - -fn tail_recursive_range(start: Int, stop: Int, acc: List(Int)) -> List(Int) { - case int.compare(start, stop) { - order.Eq -> [stop, ..acc] - order.Gt -> tail_recursive_range(start, stop + 1, [stop, ..acc]) - order.Lt -> tail_recursive_range(start, stop - 1, [stop, ..acc]) - } -} - -fn do_repeat(item: a, times: Int, acc: List(a)) -> List(a) { - case times <= 0 { - True -> acc - False -> do_repeat(item, times - 1, [item, ..acc]) - } -} - -/// Builds a list of a given value a given number of times. -/// -/// ## Examples -/// -/// ```gleam -/// repeat("a", times: 0) -/// // -> [] -/// ``` -/// -/// ```gleam -/// repeat("a", times: 5) -/// // -> ["a", "a", "a", "a", "a"] -/// ``` -/// -pub fn repeat(item a: a, times times: Int) -> List(a) { - do_repeat(a, times, []) -} - -fn do_split(list: List(a), n: Int, taken: List(a)) -> #(List(a), List(a)) { - case n <= 0 { - True -> #(reverse(taken), list) - False -> - case list { - [] -> #(reverse(taken), []) - [first, ..rest] -> do_split(rest, n - 1, [first, ..taken]) - } - } -} - -/// Splits a list in two before the given index. -/// -/// If the list is not long enough to have the given index the before list will -/// be the input list, and the after list will be empty. -/// -/// ## Examples -/// -/// ```gleam -/// split([6, 7, 8, 9], 0) -/// // -> #([], [6, 7, 8, 9]) -/// ``` -/// -/// ```gleam -/// split([6, 7, 8, 9], 2) -/// // -> #([6, 7], [8, 9]) -/// ``` -/// -/// ```gleam -/// split([6, 7, 8, 9], 4) -/// // -> #([6, 7, 8, 9], []) -/// ``` -/// -pub fn split(list list: List(a), at index: Int) -> #(List(a), List(a)) { - do_split(list, index, []) -} - -fn do_split_while( - list: List(a), - f: fn(a) -> Bool, - acc: List(a), -) -> #(List(a), List(a)) { - case list { - [] -> #(reverse(acc), []) - [first, ..rest] -> - case f(first) { - False -> #(reverse(acc), list) - _ -> do_split_while(rest, f, [first, ..acc]) - } - } -} - -/// Splits a list in two before the first element that a given function returns -/// `False` for. -/// -/// If the function returns `True` for all elements the first list will be the -/// input list, and the second list will be empty. -/// -/// ## Examples -/// -/// ```gleam -/// split_while([1, 2, 3, 4, 5], fn(x) { x <= 3 }) -/// // -> #([1, 2, 3], [4, 5]) -/// ``` -/// -/// ```gleam -/// split_while([1, 2, 3, 4, 5], fn(x) { x <= 5 }) -/// // -> #([1, 2, 3, 4, 5], []) -/// ``` -/// -pub fn split_while( - list list: List(a), - satisfying predicate: fn(a) -> Bool, -) -> #(List(a), List(a)) { - do_split_while(list, predicate, []) -} - -/// Given a list of 2-element tuples, finds the first tuple that has a given -/// key as the first element and returns the second element. -/// -/// If no tuple is found with the given key then `Error(Nil)` is returned. -/// -/// This function may be useful for interacting with Erlang code where lists of -/// tuples are common. -/// -/// ## Examples -/// -/// ```gleam -/// key_find([#("a", 0), #("b", 1)], "a") -/// // -> Ok(0) -/// ``` -/// -/// ```gleam -/// key_find([#("a", 0), #("b", 1)], "b") -/// // -> Ok(1) -/// ``` -/// -/// ```gleam -/// key_find([#("a", 0), #("b", 1)], "c") -/// // -> Error(Nil) -/// ``` -/// -pub fn key_find( - in keyword_list: List(#(k, v)), - find desired_key: k, -) -> Result(v, Nil) { - find_map(keyword_list, fn(keyword) { - let #(key, value) = keyword - case key == desired_key { - True -> Ok(value) - False -> Error(Nil) - } - }) -} - -/// Given a list of 2-element tuples, finds all tuples that have a given -/// key as the first element and returns the second element. -/// -/// This function may be useful for interacting with Erlang code where lists of -/// tuples are common. -/// -/// ## Examples -/// -/// ```gleam -/// key_filter([#("a", 0), #("b", 1), #("a", 2)], "a") -/// // -> [0, 2] -/// ``` -/// -/// ```gleam -/// key_filter([#("a", 0), #("b", 1)], "c") -/// // -> [] -/// ``` -/// -pub fn key_filter( - in keyword_list: List(#(k, v)), - find desired_key: k, -) -> List(v) { - filter_map(keyword_list, fn(keyword) { - let #(key, value) = keyword - case key == desired_key { - True -> Ok(value) - False -> Error(Nil) - } - }) -} - -fn do_pop(haystack, predicate, checked) { - case haystack { - [] -> Error(Nil) - [x, ..rest] -> - case predicate(x) { - True -> Ok(#(x, append(reverse(checked), rest))) - False -> do_pop(rest, predicate, [x, ..checked]) - } - } -} - -/// Removes the first element in a given list for which the predicate function returns `True`. -/// -/// Returns `Error(Nil)` if no such element is found. -/// -/// ## Examples -/// -/// ```gleam -/// pop([1, 2, 3], fn(x) { x > 2 }) -/// // -> Ok(#(3, [1, 2])) -/// ``` -/// -/// ```gleam -/// pop([1, 2, 3], fn(x) { x > 4 }) -/// // -> Error(Nil) -/// ``` -/// -/// ```gleam -/// pop([], fn(_) { True }) -/// // -> Error(Nil) -/// ``` -/// -pub fn pop( - in list: List(a), - one_that is_desired: fn(a) -> Bool, -) -> Result(#(a, List(a)), Nil) { - do_pop(list, is_desired, []) -} - -fn do_pop_map( - list: List(a), - mapper: fn(a) -> Result(b, e), - checked: List(a), -) -> Result(#(b, List(a)), Nil) { - case list { - [] -> Error(Nil) - [x, ..rest] -> - case mapper(x) { - Ok(y) -> Ok(#(y, append(reverse(checked), rest))) - Error(_) -> do_pop_map(rest, mapper, [x, ..checked]) - } - } -} - -/// Removes the first element in a given list for which the given function returns -/// `Ok(new_value)`, then returns the wrapped `new_value` as well as list with the value removed. -/// -/// Returns `Error(Nil)` if no such element is found. -/// -/// ## Examples -/// -/// ```gleam -/// pop_map([[], [2], [3]], first) -/// // -> Ok(#(2, [[], [3]])) -/// ``` -/// -/// ```gleam -/// pop_map([[], []], first) -/// // -> Error(Nil) -/// ``` -/// -/// ```gleam -/// pop_map([], first) -/// // -> Error(Nil) -/// ``` -/// -pub fn pop_map( - in haystack: List(a), - one_that is_desired: fn(a) -> Result(b, c), -) -> Result(#(b, List(a)), Nil) { - do_pop_map(haystack, is_desired, []) -} - -/// Given a list of 2-element tuples, finds the first tuple that has a given -/// key as the first element. This function will return the second element -/// of the found tuple and list with tuple removed. -/// -/// If no tuple is found with the given key then `Error(Nil)` is returned. -/// -/// ## Examples -/// -/// ```gleam -/// key_pop([#("a", 0), #("b", 1)], "a") -/// // -> Ok(#(0, [#("b", 1)])) -/// ``` -/// -/// ```gleam -/// key_pop([#("a", 0), #("b", 1)], "b") -/// // -> Ok(#(1, [#("a", 0)])) -/// ``` -/// -/// ```gleam -/// key_pop([#("a", 0), #("b", 1)], "c") -/// // -> Error(Nil) -/// ``` -/// -pub fn key_pop(list: List(#(k, v)), key: k) -> Result(#(v, List(#(k, v))), Nil) { - pop_map(list, fn(entry) { - let #(k, v) = entry - case k { - k if k == key -> Ok(v) - _ -> Error(Nil) - } - }) -} - -/// Given a list of 2-element tuples, inserts a key and value into the list. -/// -/// If there was already a tuple with the key then it is replaced, otherwise it -/// is added to the end of the list. -/// -/// ## Examples -/// -/// ```gleam -/// key_set([#(5, 0), #(4, 1)], 4, 100) -/// // -> [#(5, 0), #(4, 100)] -/// ``` -/// -/// ```gleam -/// key_set([#(5, 0), #(4, 1)], 1, 100) -/// // -> [#(5, 0), #(4, 1), #(1, 100)] -/// ``` -/// -pub fn key_set(list: List(#(k, v)), key: k, value: v) -> List(#(k, v)) { - case list { - [] -> [#(key, value)] - [#(k, _), ..rest] if k == key -> [#(key, value), ..rest] - [first, ..rest] -> [first, ..key_set(rest, key, value)] - } -} - -/// Calls a function for each element in a list, discarding the return value. -/// -/// Useful for calling a side effect for every item of a list. -/// -/// ```gleam -/// import gleam/io -/// -/// each(["1", "2", "3"], io.println) -/// // -> Nil -/// // 1 -/// // 2 -/// // 3 -/// ``` -/// -pub fn each(list: List(a), f: fn(a) -> b) -> Nil { - case list { - [] -> Nil - [first, ..rest] -> { - f(first) - each(rest, f) - } - } -} - -/// Calls a `Result` returning function for each element in a list, discarding -/// the return value. If the function returns `Error` then the iteration is -/// stopped and the error is returned. -/// -/// Useful for calling a side effect for every item of a list. -/// -/// ## Examples -/// -/// ```gleam -/// try_each( -/// over: [1, 2, 3], -/// with: function_that_might_fail, -/// ) -/// // -> Ok(Nil) -/// ``` -/// -pub fn try_each( - over list: List(a), - with fun: fn(a) -> Result(b, e), -) -> Result(Nil, e) { - case list { - [] -> Ok(Nil) - [first, ..rest] -> - case fun(first) { - Ok(_) -> try_each(over: rest, with: fun) - Error(e) -> Error(e) - } - } -} - -fn do_partition(list, categorise, trues, falses) { - case list { - [] -> #(reverse(trues), reverse(falses)) - [first, ..rest] -> - case categorise(first) { - True -> do_partition(rest, categorise, [first, ..trues], falses) - False -> do_partition(rest, categorise, trues, [first, ..falses]) - } - } -} - -/// Partitions a list into a tuple/pair of lists -/// by a given categorisation function. -/// -/// ## Examples -/// -/// ```gleam -/// import gleam/int -/// -/// [1, 2, 3, 4, 5] |> partition(int.is_odd) -/// // -> #([1, 3, 5], [2, 4]) -/// ``` -/// -pub fn partition( - list: List(a), - with categorise: fn(a) -> Bool, -) -> #(List(a), List(a)) { - do_partition(list, categorise, [], []) -} - -/// Returns all the permutations of a list. -/// -/// ## Examples -/// -/// ```gleam -/// permutations([1, 2]) -/// // -> [[1, 2], [2, 1]] -/// ``` -/// -pub fn permutations(list: List(a)) -> List(List(a)) { - case list { - [] -> [[]] - _ -> - index_map(list, fn(i, i_idx) { - index_fold(list, [], fn(acc, j, j_idx) { - case i_idx == j_idx { - True -> acc - False -> [j, ..acc] - } - }) - |> reverse - |> permutations - |> map(fn(permutation) { [i, ..permutation] }) - }) - |> flatten - } -} - -fn do_window(acc: List(List(a)), list: List(a), n: Int) -> List(List(a)) { - let window = take(list, n) - - case length(window) == n { - True -> do_window([window, ..acc], drop(list, 1), n) - False -> acc - } -} - -/// Returns a list of sliding windows. -/// -/// ## Examples -/// -/// ```gleam -/// window([1,2,3,4,5], 3) -/// // -> [[1, 2, 3], [2, 3, 4], [3, 4, 5]] -/// ``` -/// -/// ```gleam -/// window([1, 2], 4) -/// // -> [] -/// ``` -/// -pub fn window(list: List(a), by n: Int) -> List(List(a)) { - case n <= 0 { - True -> [] - False -> do_window([], list, n) |> reverse - } -} - -/// Returns a list of tuples containing two contiguous elements. -/// -/// ## Examples -/// -/// ```gleam -/// window_by_2([1,2,3,4]) -/// // -> [#(1, 2), #(2, 3), #(3, 4)] -/// ``` -/// -/// ```gleam -/// window_by_2([1]) -/// // -> [] -/// ``` -/// -pub fn window_by_2(list: List(a)) -> List(#(a, a)) { - zip(list, drop(list, 1)) -} - -/// Drops the first elements in a given list for which the predicate function returns `True`. -/// -/// ## Examples -/// -/// ```gleam -/// drop_while([1, 2, 3, 4], fn (x) { x < 3 }) -/// // -> [3, 4] -/// ``` -/// -pub fn drop_while( - in list: List(a), - satisfying predicate: fn(a) -> Bool, -) -> List(a) { - case list { - [] -> [] - [first, ..rest] -> - case predicate(first) { - True -> drop_while(rest, predicate) - False -> [first, ..rest] - } - } -} - -fn do_take_while( - list: List(a), - predicate: fn(a) -> Bool, - acc: List(a), -) -> List(a) { - case list { - [] -> reverse(acc) - [first, ..rest] -> - case predicate(first) { - True -> do_take_while(rest, predicate, [first, ..acc]) - False -> reverse(acc) - } - } -} - -/// Takes the first elements in a given list for which the predicate function returns `True`. -/// -/// ## Examples -/// -/// ```gleam -/// take_while([1, 2, 3, 2, 4], fn (x) { x < 3 }) -/// // -> [1, 2] -/// ``` -/// -pub fn take_while( - in list: List(a), - satisfying predicate: fn(a) -> Bool, -) -> List(a) { - do_take_while(list, predicate, []) -} - -fn do_chunk( - list: List(a), - f: fn(a) -> k, - previous_key: k, - current_chunk: List(a), - acc: List(List(a)), -) -> List(List(a)) { - case list { - [first, ..rest] -> { - let key = f(first) - case key == previous_key { - False -> { - let new_acc = [reverse(current_chunk), ..acc] - do_chunk(rest, f, key, [first], new_acc) - } - _true -> do_chunk(rest, f, key, [first, ..current_chunk], acc) - } - } - _empty -> reverse([reverse(current_chunk), ..acc]) - } -} - -/// Returns a list of chunks in which -/// the return value of calling `f` on each element is the same. -/// -/// ## Examples -/// -/// ```gleam -/// [1, 2, 2, 3, 4, 4, 6, 7, 7] |> chunk(by: fn(n) { n % 2 }) -/// // -> [[1], [2, 2], [3], [4, 4, 6], [7, 7]] -/// ``` -/// -pub fn chunk(in list: List(a), by f: fn(a) -> k) -> List(List(a)) { - case list { - [] -> [] - [first, ..rest] -> do_chunk(rest, f, f(first), [first], []) - } -} - -fn do_sized_chunk( - list: List(a), - count: Int, - left: Int, - current_chunk: List(a), - acc: List(List(a)), -) -> List(List(a)) { - case list { - [] -> - case current_chunk { - [] -> reverse(acc) - remaining -> reverse([reverse(remaining), ..acc]) - } - [first, ..rest] -> { - let chunk = [first, ..current_chunk] - case left > 1 { - False -> do_sized_chunk(rest, count, count, [], [reverse(chunk), ..acc]) - True -> do_sized_chunk(rest, count, left - 1, chunk, acc) - } - } - } -} - -/// Returns a list of chunks containing `count` elements each. -/// -/// If the last chunk does not have `count` elements, it is instead -/// a partial chunk, with less than `count` elements. -/// -/// For any `count` less than 1 this function behaves as if it was set to 1. -/// -/// ## Examples -/// -/// ```gleam -/// [1, 2, 3, 4, 5, 6] |> sized_chunk(into: 2) -/// // -> [[1, 2], [3, 4], [5, 6]] -/// ``` -/// -/// ```gleam -/// [1, 2, 3, 4, 5, 6, 7, 8] |> sized_chunk(into: 3) -/// // -> [[1, 2, 3], [4, 5, 6], [7, 8]] -/// ``` -/// -pub fn sized_chunk(in list: List(a), into count: Int) -> List(List(a)) { - do_sized_chunk(list, count, count, [], []) -} - -/// This function acts similar to fold, but does not take an initial state. -/// Instead, it starts from the first element in the list -/// and combines it with each subsequent element in turn using the given -/// function. The function is called as `fun(accumulator, current_element)`. -/// -/// Returns `Ok` to indicate a successful run, and `Error` if called on an -/// empty list. -/// -/// ## Examples -/// -/// ```gleam -/// [] |> reduce(fn(acc, x) { acc + x }) -/// // -> Error(Nil) -/// ``` -/// -/// ```gleam -/// [1, 2, 3, 4, 5] |> reduce(fn(acc, x) { acc + x }) -/// // -> Ok(15) -/// ``` -/// -pub fn reduce(over list: List(a), with fun: fn(a, a) -> a) -> Result(a, Nil) { - case list { - [] -> Error(Nil) - [first, ..rest] -> Ok(fold(rest, first, fun)) - } -} - -fn do_scan( - list: List(a), - accumulator: acc, - accumulated: List(acc), - fun: fn(acc, a) -> acc, -) -> List(acc) { - case list { - [] -> reverse(accumulated) - [first, ..rest] -> { - let next = fun(accumulator, first) - do_scan(rest, next, [next, ..accumulated], fun) - } - } -} - -/// Similar to `fold`, but yields the state of the accumulator at each stage. -/// -/// ## Examples -/// -/// ```gleam -/// scan(over: [1, 2, 3], from: 100, with: fn(acc, i) { acc + i }) -/// // -> [101, 103, 106] -/// ``` -/// -pub fn scan( - over list: List(a), - from initial: acc, - with fun: fn(acc, a) -> acc, -) -> List(acc) { - do_scan(list, initial, [], fun) -} - -/// Returns the last element in the given list. -/// -/// Returns `Error(Nil)` if the list is empty. -/// -/// This function runs in linear time. -/// For a collection oriented around performant access at either end, -/// see `gleam/queue.Queue`. -/// -/// ## Examples -/// -/// ```gleam -/// last([]) -/// // -> Error(Nil) -/// ``` -/// -/// ```gleam -/// last([1, 2, 3, 4, 5]) -/// // -> Ok(5) -/// ``` -/// -pub fn last(list: List(a)) -> Result(a, Nil) { - list - |> reduce(fn(_, elem) { elem }) -} - -/// Return unique combinations of elements in the list. -/// -/// ## Examples -/// -/// ```gleam -/// combinations([1, 2, 3], 2) -/// // -> [[1, 2], [1, 3], [2, 3]] -/// ``` -/// -/// ```gleam -/// combinations([1, 2, 3, 4], 3) -/// // -> [[1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]] -/// ``` -/// -pub fn combinations(items: List(a), by n: Int) -> List(List(a)) { - case n { - 0 -> [[]] - _ -> - case items { - [] -> [] - [first, ..rest] -> { - let first_combinations = - map(combinations(rest, n - 1), with: fn(com) { [first, ..com] }) - |> reverse - fold(first_combinations, combinations(rest, n), fn(acc, c) { - [c, ..acc] - }) - } - } - } -} - -fn do_combination_pairs(items: List(a)) -> List(List(#(a, a))) { - case items { - [] -> [] - [first, ..rest] -> { - let first_combinations = map(rest, with: fn(other) { #(first, other) }) - [first_combinations, ..do_combination_pairs(rest)] - } - } -} - -/// Return unique pair combinations of elements in the list -/// -/// ## Examples -/// -/// ```gleam -/// combination_pairs([1, 2, 3]) -/// // -> [#(1, 2), #(1, 3), #(2, 3)] -/// ``` -/// -pub fn combination_pairs(items: List(a)) -> List(#(a, a)) { - do_combination_pairs(items) - |> flatten -} - -/// Make a list alternating the elements from the given lists -/// -/// ## Examples -/// -/// ```gleam -/// interleave([[1, 2], [101, 102], [201, 202]]) -/// // -> [1, 101, 201, 2, 102, 202] -/// ``` -/// -pub fn interleave(list: List(List(a))) -> List(a) { - transpose(list) - |> flatten -} - -/// Transpose rows and columns of the list of lists. -/// -/// Notice: This function is not tail recursive, -/// and thus may exceed stack size if called, -/// with large lists (on target JavaScript). -/// -/// ## Examples -/// -/// ```gleam -/// transpose([[1, 2, 3], [101, 102, 103]]) -/// // -> [[1, 101], [2, 102], [3, 103]] -/// ``` -/// -pub fn transpose(list_of_list: List(List(a))) -> List(List(a)) { - let take_first = fn(list) { - case list { - [] -> [] - [f] -> [f] - [f, ..] -> [f] - } - } - - case list_of_list { - [] -> [] - [[], ..rest] -> transpose(rest) - rows -> { - let firsts = - rows - |> map(take_first) - |> flatten - let rest = transpose(map(rows, drop(_, 1))) - [firsts, ..rest] - } - } -} - -fn do_shuffle_pair_unwrap(list: List(#(Float, a)), acc: List(a)) -> List(a) { - case list { - [] -> acc - [elem_pair, ..enumerable] -> - do_shuffle_pair_unwrap(enumerable, [elem_pair.1, ..acc]) - } -} - -fn do_shuffle_by_pair_indexes( - list_of_pairs: List(#(Float, a)), -) -> List(#(Float, a)) { - sort(list_of_pairs, fn(a_pair: #(Float, a), b_pair: #(Float, a)) -> Order { - float.compare(a_pair.0, b_pair.0) - }) -} - -/// Takes a list, randomly sorts all items and returns the shuffled list. -/// -/// This function uses `float.random` to decide the order of the elements. -/// -/// ## Example -/// -/// ```gleam -/// range(1, 10) |> shuffle() -/// // -> [1, 6, 9, 10, 3, 8, 4, 2, 7, 5] -/// ``` -/// -pub fn shuffle(list: List(a)) -> List(a) { - list - |> fold(from: [], with: fn(acc, a) { [#(float.random(), a), ..acc] }) - |> do_shuffle_by_pair_indexes() - |> do_shuffle_pair_unwrap([]) -} diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/option.gleam b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/option.gleam deleted file mode 100644 index 7ada122b519..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/option.gleam +++ /dev/null @@ -1,358 +0,0 @@ -/// `Option` represents a value that may be present or not. `Some` means the value is -/// present, `None` means the value is not. -/// -/// This is Gleam's alternative to having a value that could be Null, as is -/// possible in some other languages. -/// -/// ## `Option` and `Result` -/// -/// In other languages failible functions may return either `Result` or -/// `Option` depending on whether there is more information to be given about the -/// failure. In Gleam all failible functions return `Result`, and `Nil` is used -/// as the error if there is no extra detail to give. This consistency removes -/// the boilerplate that would otherwise be needed to convert between `Option` -/// and `Result` types, and makes APIs more predictable. -/// -/// The `Option` type should only be used for taking optional values as -/// function arguments, or for storing them in other data structures. -/// -pub type Option(a) { - Some(a) - None -} - -fn do_all(list: List(Option(a)), acc: List(a)) -> Option(List(a)) { - case list { - [] -> Some(acc) - [x, ..rest] -> { - let accumulate = fn(acc, item) { - case acc, item { - Some(values), Some(value) -> Some([value, ..values]) - _, _ -> None - } - } - accumulate(do_all(rest, acc), x) - } - } -} - -/// Combines a list of `Option`s into a single `Option`. -/// If all elements in the list are `Some` then returns a `Some` holding the list of values. -/// If any element is `None` then returns`None`. -/// -/// ## Examples -/// -/// ```gleam -/// all([Some(1), Some(2)]) -/// // -> Some([1, 2]) -/// ``` -/// -/// ```gleam -/// all([Some(1), None]) -/// // -> None -/// ``` -/// -pub fn all(list: List(Option(a))) -> Option(List(a)) { - do_all(list, []) -} - -/// Checks whether the `Option` is a `Some` value. -/// -/// ## Examples -/// -/// ```gleam -/// is_some(Some(1)) -/// // -> True -/// ``` -/// -/// ```gleam -/// is_some(None) -/// // -> False -/// ``` -/// -pub fn is_some(option: Option(a)) -> Bool { - option != None -} - -/// Checks whether the `Option` is a `None` value. -/// -/// ## Examples -/// -/// ```gleam -/// is_none(Some(1)) -/// // -> False -/// ``` -/// -/// ```gleam -/// is_none(None) -/// // -> True -/// ``` -/// -pub fn is_none(option: Option(a)) -> Bool { - option == None -} - -/// Converts an `Option` type to a `Result` type. -/// -/// ## Examples -/// -/// ```gleam -/// to_result(Some(1), "some_error") -/// // -> Ok(1) -/// ``` -/// -/// ```gleam -/// to_result(None, "some_error") -/// // -> Error("some_error") -/// ``` -/// -pub fn to_result(option: Option(a), e) -> Result(a, e) { - case option { - Some(a) -> Ok(a) - _ -> Error(e) - } -} - -/// Converts a `Result` type to an `Option` type. -/// -/// ## Examples -/// -/// ```gleam -/// from_result(Ok(1)) -/// // -> Some(1) -/// ``` -/// -/// ```gleam -/// from_result(Error("some_error")) -/// // -> None -/// ``` -/// -pub fn from_result(result: Result(a, e)) -> Option(a) { - case result { - Ok(a) -> Some(a) - _ -> None - } -} - -/// Extracts the value from an `Option`, returning a default value if there is none. -/// -/// ## Examples -/// -/// ```gleam -/// unwrap(Some(1), 0) -/// // -> 1 -/// ``` -/// -/// ```gleam -/// unwrap(None, 0) -/// // -> 0 -/// ``` -/// -pub fn unwrap(option: Option(a), or default: a) -> a { - case option { - Some(x) -> x - None -> default - } -} - -/// Extracts the value from an `Option`, evaluating the default function if the option is `None`. -/// -/// ## Examples -/// -/// ```gleam -/// lazy_unwrap(Some(1), fn() { 0 }) -/// // -> 1 -/// ``` -/// -/// ```gleam -/// lazy_unwrap(None, fn() { 0 }) -/// // -> 0 -/// ``` -/// -pub fn lazy_unwrap(option: Option(a), or default: fn() -> a) -> a { - case option { - Some(x) -> x - None -> default() - } -} - -/// Updates a value held within the `Some` of an `Option` by calling a given function -/// on it. -/// -/// If the `Option` is a `None` rather than `Some`, the function is not called and the -/// `Option` stays the same. -/// -/// ## Examples -/// -/// ```gleam -/// map(over: Some(1), with: fn(x) { x + 1 }) -/// // -> Some(2) -/// ``` -/// -/// ```gleam -/// map(over: None, with: fn(x) { x + 1 }) -/// // -> None -/// ``` -/// -pub fn map(over option: Option(a), with fun: fn(a) -> b) -> Option(b) { - case option { - Some(x) -> Some(fun(x)) - None -> None - } -} - -/// Merges a nested `Option` into a single layer. -/// -/// ## Examples -/// -/// ```gleam -/// flatten(Some(Some(1))) -/// // -> Some(1) -/// ``` -/// -/// ```gleam -/// flatten(Some(None)) -/// // -> None -/// ``` -/// -/// ```gleam -/// flatten(None) -/// // -> None -/// ``` -/// -pub fn flatten(option: Option(Option(a))) -> Option(a) { - case option { - Some(x) -> x - None -> None - } -} - -/// Updates a value held within the `Some` of an `Option` by calling a given function -/// on it, where the given function also returns an `Option`. The two options are -/// then merged together into one `Option`. -/// -/// If the `Option` is a `None` rather than `Some` the function is not called and the -/// option stays the same. -/// -/// This function is the equivalent of calling `map` followed by `flatten`, and -/// it is useful for chaining together multiple functions that return `Option`. -/// -/// ## Examples -/// -/// ```gleam -/// then(Some(1), fn(x) { Some(x + 1) }) -/// // -> Some(2) -/// ``` -/// -/// ```gleam -/// then(Some(1), fn(x) { Some(#("a", x)) }) -/// // -> Some(#("a", 1)) -/// ``` -/// -/// ```gleam -/// then(Some(1), fn(_) { None }) -/// // -> None -/// ``` -/// -/// ```gleam -/// then(None, fn(x) { Some(x + 1) }) -/// // -> None -/// ``` -/// -pub fn then(option: Option(a), apply fun: fn(a) -> Option(b)) -> Option(b) { - case option { - Some(x) -> fun(x) - None -> None - } -} - -/// Returns the first value if it is `Some`, otherwise returns the second value. -/// -/// ## Examples -/// -/// ```gleam -/// or(Some(1), Some(2)) -/// // -> Some(1) -/// ``` -/// -/// ```gleam -/// or(Some(1), None) -/// // -> Some(1) -/// ``` -/// -/// ```gleam -/// or(None, Some(2)) -/// // -> Some(2) -/// ``` -/// -/// ```gleam -/// or(None, None) -/// // -> None -/// ``` -/// -pub fn or(first: Option(a), second: Option(a)) -> Option(a) { - case first { - Some(_) -> first - None -> second - } -} - -/// Returns the first value if it is `Some`, otherwise evaluates the given function for a fallback value. -/// -/// ## Examples -/// -/// ```gleam -/// lazy_or(Some(1), fn() { Some(2) }) -/// // -> Some(1) -/// ``` -/// -/// ```gleam -/// lazy_or(Some(1), fn() { None }) -/// // -> Some(1) -/// ``` -/// -/// ```gleam -/// lazy_or(None, fn() { Some(2) }) -/// // -> Some(2) -/// ``` -/// -/// ```gleam -/// lazy_or(None, fn() { None }) -/// // -> None -/// ``` -/// -pub fn lazy_or(first: Option(a), second: fn() -> Option(a)) -> Option(a) { - case first { - Some(_) -> first - None -> second() - } -} - -fn do_values(list: List(Option(a)), acc: List(a)) -> List(a) { - case list { - [] -> acc - [first, ..rest] -> { - let accumulate = fn(acc, item) { - case item { - Some(value) -> [value, ..acc] - None -> acc - } - } - accumulate(do_values(rest, acc), first) - } - } -} - -/// Given a list of `Option`s, -/// returns only the values inside `Some`. -/// -/// ## Examples -/// -/// ```gleam -/// values([Some(1), None, Some(3)]) -/// // -> [1, 3] -/// ``` -/// -pub fn values(options: List(Option(a))) -> List(a) { - do_values(options, []) -} diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/order.gleam b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/order.gleam deleted file mode 100644 index be8b5994e98..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/order.gleam +++ /dev/null @@ -1,156 +0,0 @@ -/// Represents the result of a single comparison to determine the precise -/// ordering of two values. -/// -pub type Order { - /// Less-than - Lt - - /// Equal - Eq - - /// Greater than - Gt -} - -/// Inverts an order, so less-than becomes greater-than and greater-than -/// becomes less-than. -/// -/// ## Examples -/// -/// ```gleam -/// negate(Lt) -/// // -> Gt -/// ``` -/// -/// ```gleam -/// negate(Eq) -/// // -> Eq -/// ``` -/// -/// ```gleam -/// negate(Gt) -/// // -> Lt -/// ``` -/// -pub fn negate(order: Order) -> Order { - case order { - Lt -> Gt - Eq -> Eq - Gt -> Lt - } -} - -/// Produces a numeric representation of the order. -/// -/// ## Examples -/// -/// ```gleam -/// to_int(Lt) -/// // -> -1 -/// ``` -/// -/// ```gleam -/// to_int(Eq) -/// // -> 0 -/// ``` -/// -/// ```gleam -/// to_int(Gt) -/// // -> 1 -/// ``` -/// -pub fn to_int(order: Order) -> Int { - case order { - Lt -> -1 - Eq -> 0 - Gt -> 1 - } -} - -/// Compares two `Order` values to one another, producing a new `Order`. -/// -/// ## Examples -/// -/// ```gleam -/// compare(Eq, with: Lt) -/// // -> Gt -/// ``` -/// -pub fn compare(a: Order, with b: Order) -> Order { - case a, b { - x, y if x == y -> Eq - Lt, _ | Eq, Gt -> Lt - _, _ -> Gt - } -} - -/// Inverts an ordering function, so less-than becomes greater-than and greater-than -/// becomes less-than. -/// -/// ## Examples -/// -/// ```gleam -/// import gleam/int -/// import gleam/list -/// -/// list.sort([1, 5, 4], by: reverse(int.compare)) -/// // -> [5, 4, 1] -/// ``` -/// -pub fn reverse(orderer: fn(a, a) -> Order) -> fn(a, a) -> Order { - fn(a, b) { orderer(b, a) } -} - -/// Return a fallback `Order` in case the first argument is `Eq`. -/// -/// ## Examples -/// -/// ```gleam -/// import gleam/int -/// -/// break_tie(in: int.compare(1, 1), with: Lt) -/// // -> Lt -/// ``` -/// -/// ```gleam -/// import gleam/int -/// -/// break_tie(in: int.compare(1, 0), with: Eq) -/// // -> Gt -/// ``` -/// -pub fn break_tie(in order: Order, with other: Order) -> Order { - case order { - Lt | Gt -> order - Eq -> other - } -} - -/// Invokes a fallback function returning an `Order` in case the first argument -/// is `Eq`. -/// -/// This can be useful when the fallback comparison might be expensive and it -/// needs to be delayed until strictly necessary. -/// -/// ## Examples -/// -/// ```gleam -/// import gleam/int -/// -/// lazy_break_tie(in: int.compare(1, 1), with: fn() { Lt }) -/// // -> Lt -/// ``` -/// -/// ```gleam -/// import gleam/int -/// -/// lazy_break_tie(in: int.compare(1, 0), with: fn() { Eq }) -/// // -> Gt -/// ``` -/// -pub fn lazy_break_tie(in order: Order, with comparison: fn() -> Order) -> Order { - case order { - Lt | Gt -> order - Eq -> comparison() - } -} diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/pair.gleam b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/pair.gleam deleted file mode 100644 index 566fc9c4e50..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/pair.gleam +++ /dev/null @@ -1,85 +0,0 @@ -/// Returns the first element in a pair. -/// -/// ## Examples -/// -/// ```gleam -/// first(#(1, 2)) -/// // -> 1 -/// ``` -/// -pub fn first(pair: #(a, b)) -> a { - let #(a, _) = pair - a -} - -/// Returns the second element in a pair. -/// -/// ## Examples -/// -/// ```gleam -/// second(#(1, 2)) -/// // -> 2 -/// ``` -/// -pub fn second(pair: #(a, b)) -> b { - let #(_, a) = pair - a -} - -/// Returns a new pair with the elements swapped. -/// -/// ## Examples -/// -/// ```gleam -/// swap(#(1, 2)) -/// // -> #(2, 1) -/// ``` -/// -pub fn swap(pair: #(a, b)) -> #(b, a) { - let #(a, b) = pair - #(b, a) -} - -/// Returns a new pair with the first element having had `with` applied to -/// it. -/// -/// ## Examples -/// -/// ```gleam -/// #(1, 2) |> map_first(fn(n) { n * 2 }) -/// // -> #(2, 2) -/// ``` -/// -pub fn map_first(of pair: #(a, b), with fun: fn(a) -> c) -> #(c, b) { - let #(a, b) = pair - #(fun(a), b) -} - -/// Returns a new pair with the second element having had `with` applied to -/// it. -/// -/// ## Examples -/// -/// ```gleam -/// #(1, 2) |> map_second(fn(n) { n * 2 }) -/// // -> #(1, 4) -/// ``` -/// -pub fn map_second(of pair: #(a, b), with fun: fn(b) -> c) -> #(a, c) { - let #(a, b) = pair - #(a, fun(b)) -} - -/// Returns a new pair with the given elements. This can also be done using the dedicated -/// syntax instead: `new(1, 2) == #(1, 2)`. -/// -/// ## Examples -/// -/// ```gleam -/// new(1, 2) -/// // -> #(1, 2) -/// ``` -/// -pub fn new(first: a, second: b) -> #(a, b) { - #(first, second) -} diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/queue.gleam b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/queue.gleam deleted file mode 100644 index 62e62a804be..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/queue.gleam +++ /dev/null @@ -1,290 +0,0 @@ -import gleam/list - -/// A queue is an ordered collection of elements. It is similar to a list, but -/// unlike a list elements can be added to or removed from either the front or -/// the back in a performant fashion. -/// -/// The internal representation may be different for two queues with the same -/// elements in the same order if the queues were constructed in different -/// ways. This is the price paid for a queue's fast access at both the front -/// and the back. -/// -/// Because of unpredictable internal representation the equality operator `==` -/// may return surprising results, and the `is_equal` and `is_logically_equal` -/// functions are the recommended way to test queues for equality. -/// -pub opaque type Queue(a) { - Queue(in: List(a), out: List(a)) -} - -/// Creates a fresh queue that contains no values. -/// -pub fn new() -> Queue(a) { - Queue(in: [], out: []) -} - -/// Converts a list of elements into a queue of the same elements in the same -/// order. The first element in the list becomes the front element in the queue. -/// -/// This function runs in constant time. -/// -/// # Examples -/// -/// ```gleam -/// [1, 2, 3] |> from_list |> length -/// // -> 3 -/// ``` -/// -pub fn from_list(list: List(a)) -> Queue(a) { - Queue(in: [], out: list) -} - -/// Converts a queue of elements into a list of the same elements in the same -/// order. The front element in the queue becomes the first element in the list. -/// -/// This function runs in linear time. -/// -/// # Examples -/// -/// ```gleam -/// new() |> push_back(1) |> push_back(2) |> to_list -/// // -> [1, 2] -/// ``` -/// -pub fn to_list(queue: Queue(a)) -> List(a) { - queue.out - |> list.append(list.reverse(queue.in)) -} - -/// Determines whether or not the queue is empty. -/// -/// This function runs in constant time. -/// -/// ## Examples -/// -/// ```gleam -/// [] |> from_list |> is_empty -/// // -> True -/// ``` -/// -/// ```gleam -/// [1] |> from_list |> is_empty -/// // -> False -/// ``` -/// -/// ```gleam -/// [1, 2] |> from_list |> is_empty -/// // -> False -/// ``` -/// -pub fn is_empty(queue: Queue(a)) -> Bool { - queue.in == [] && queue.out == [] -} - -/// Counts the number of elements in a given queue. -/// -/// This function has to traverse the queue to determine the number of elements, -/// so it runs in linear time. -/// -/// ## Examples -/// -/// ```gleam -/// length(from_list([])) -/// // -> 0 -/// ``` -/// -/// ```gleam -/// length(from_list([1])) -/// // -> 1 -/// ``` -/// -/// ```gleam -/// length(from_list([1, 2])) -/// // -> 2 -/// ``` -/// -pub fn length(queue: Queue(a)) -> Int { - list.length(queue.in) + list.length(queue.out) -} - -/// Pushes an element onto the back of the queue. -/// -/// # Examples -/// -/// ```gleam -/// [1, 2] |> from_list |> push_back(3) |> to_list -/// // -> [1, 2, 3] -/// ``` -/// -pub fn push_back(onto queue: Queue(a), this item: a) -> Queue(a) { - Queue(in: [item, ..queue.in], out: queue.out) -} - -/// Pushes an element onto the front of the queue. -/// -/// # Examples -/// -/// ```gleam -/// [0, 0] |> from_list |> push_front(1) |> to_list -/// // -> [1, 0, 0] -/// ``` -/// -pub fn push_front(onto queue: Queue(a), this item: a) -> Queue(a) { - Queue(in: queue.in, out: [item, ..queue.out]) -} - -/// Gets the last element from the queue, returning the -/// element and a new queue without that element. -/// -/// This function typically runs in constant time, but will occasionally run in -/// linear time. -/// -/// # Examples -/// -/// ```gleam -/// new() -/// |> push_back(0) -/// |> push_back(1) -/// |> pop_back -/// // -> Ok(#(1, push_front(new(), 0))) -/// ``` -/// -/// ```gleam -/// new() -/// |> push_front(0) -/// |> pop_back -/// // -> Ok(#(0, new())) -/// ``` -/// -/// ```gleam -/// new() |> pop_back -/// // -> Error(Nil) -/// ``` -/// -pub fn pop_back(from queue: Queue(a)) -> Result(#(a, Queue(a)), Nil) { - case queue { - Queue(in: [], out: []) -> Error(Nil) - Queue(in: [], out: out) -> pop_back(Queue(in: list.reverse(out), out: [])) - Queue(in: [first, ..rest], out: out) -> { - let queue = Queue(in: rest, out: out) - Ok(#(first, queue)) - } - } -} - -/// Gets the first element from the queue, returning the -/// element and a new queue without that element. -/// -/// This function typically runs in constant time, but will occasionally run in -/// linear time. -/// -/// # Examples -/// -/// ```gleam -/// new() -/// |> push_front(1) -/// |> push_front(0) -/// |> pop_front -/// // -> Ok(#(0, push_back(new(), 1))) -/// ``` -/// -/// ```gleam -/// new() -/// |> push_back(0) -/// |> pop_front -/// // -> Ok(#(0, new())) -/// ``` -/// -/// ```gleam -/// new() |> pop_back -/// // -> Error(Nil) -/// ``` -/// -pub fn pop_front(from queue: Queue(a)) -> Result(#(a, Queue(a)), Nil) { - case queue { - Queue(in: [], out: []) -> Error(Nil) - Queue(in: in, out: []) -> pop_front(Queue(in: [], out: list.reverse(in))) - Queue(in: in, out: [first, ..rest]) -> { - let queue = Queue(in: in, out: rest) - Ok(#(first, queue)) - } - } -} - -/// Creates a new queue from a given queue containing the same elements, but in -/// the opposite order. -/// -/// This function runs in constant time. -/// -/// ## Examples -/// -/// ```gleam -/// [] |> from_list |> reverse |> to_list -/// // -> [] -/// ``` -/// -/// ```gleam -/// [1] |> from_list |> reverse |> to_list -/// // -> [1] -/// ``` -/// -/// ```gleam -/// [1, 2] |> from_list |> reverse |> to_list -/// // -> [2, 1] -/// ``` -/// -pub fn reverse(queue: Queue(a)) -> Queue(a) { - Queue(in: queue.out, out: queue.in) -} - -fn check_equal( - xs: List(a), - x_tail: List(a), - ys: List(a), - y_tail: List(a), - eq: fn(a, a) -> Bool, -) -> Bool { - case xs, x_tail, ys, y_tail { - [], [], [], [] -> True - [x, ..xs], _, [y, ..ys], _ -> - case eq(x, y) { - False -> False - True -> check_equal(xs, x_tail, ys, y_tail, eq) - } - [], [_, ..], _, _ -> check_equal(list.reverse(x_tail), [], ys, y_tail, eq) - _, _, [], [_, ..] -> check_equal(xs, x_tail, list.reverse(y_tail), [], eq) - _, _, _, _ -> False - } -} - -/// Checks whether two queues have equal elements in the same order, where the -/// equality of elements is determined by a given equality checking function. -/// -/// This function is useful as the internal representation may be different for -/// two queues with the same elements in the same order depending on how they -/// were constructed, so the equality operator `==` may return surprising -/// results. -/// -/// This function runs in linear time multiplied by the time taken by the -/// element equality checking function. -/// -pub fn is_logically_equal( - a: Queue(a), - to b: Queue(a), - checking element_is_equal: fn(a, a) -> Bool, -) -> Bool { - check_equal(a.out, a.in, b.out, b.in, element_is_equal) -} - -/// Checks whether two queues have the same elements in the same order. -/// -/// This function is useful as the internal representation may be different for -/// two queues with the same elements in the same order depending on how they -/// were constructed, so the equality operator `==` may return surprising -/// results. -/// -/// This function runs in linear time. -/// -pub fn is_equal(a: Queue(a), to b: Queue(a)) -> Bool { - check_equal(a.out, a.in, b.out, b.in, fn(a, b) { a == b }) -} diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/regex.gleam b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/regex.gleam deleted file mode 100644 index b3d12739379..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/regex.gleam +++ /dev/null @@ -1,219 +0,0 @@ -//// This module contains regular expression matching functions for strings. -//// The matching algorithms of the library are based on the PCRE library, but not -//// all of the PCRE library is interfaced and some parts of the library go beyond -//// what PCRE offers. Currently PCRE version 8.40 (release date 2017-01-11) is used. - -import gleam/option.{type Option} - -pub type Regex - -/// The details about a particular match: -/// -pub type Match { - Match( - /// The full string of the match. - content: String, - /// A `Regex` can have subpatterns, sup-parts that are in parentheses. - submatches: List(Option(String)), - ) -} - -/// When a regular expression fails to compile: -/// -pub type CompileError { - CompileError( - /// The problem encountered that caused the compilation to fail - error: String, - /// The byte index into the string to where the problem was found - /// This value may not be correct in JavaScript environments. - byte_index: Int, - ) -} - -pub type Options { - Options(case_insensitive: Bool, multi_line: Bool) -} - -/// Creates a `Regex` with some additional options. -/// -/// ## Examples -/// -/// ```gleam -/// let options = Options(case_insensitive: False, multi_line: True) -/// let assert Ok(re) = compile("^[0-9]", with: options) -/// check(re, "abc\n123") -/// // -> True -/// ``` -/// -/// ```gleam -/// let options = Options(case_insensitive: True, multi_line: False) -/// let assert Ok(re) = compile("[A-Z]", with: options) -/// check(re, "abc123") -/// // -> True -/// ``` -/// -pub fn compile( - pattern: String, - with options: Options, -) -> Result(Regex, CompileError) { - do_compile(pattern, options) -} - -@external(erlang, "gleam_stdlib", "compile_regex") -@external(javascript, "../gleam_stdlib.mjs", "compile_regex") -fn do_compile( - pattern: String, - with with: Options, -) -> Result(Regex, CompileError) - -/// Creates a new `Regex`. -/// -/// ## Examples -/// -/// ```gleam -/// let assert Ok(re) = from_string("[0-9]") -/// check(re, "abc123") -/// // -> True -/// ``` -/// -/// ```gleam -/// check(re, "abcxyz") -/// // -> False -/// ``` -/// -/// ```gleam -/// from_string("[0-9") -/// // -> Error(CompileError( -/// // error: "missing terminating ] for character class", -/// // byte_index: 4 -/// // )) -/// ``` -/// -pub fn from_string(pattern: String) -> Result(Regex, CompileError) { - compile(pattern, Options(case_insensitive: False, multi_line: False)) -} - -/// Returns a boolean indicating whether there was a match or not. -/// -/// ## Examples -/// -/// ```gleam -/// let assert Ok(re) = from_string("^f.o.?") -/// check(with: re, content: "foo") -/// // -> True -/// ``` -/// -/// ```gleam -/// check(with: re, content: "boo") -/// // -> False -/// ``` -/// -pub fn check(with regex: Regex, content string: String) -> Bool { - do_check(regex, string) -} - -@external(erlang, "gleam_stdlib", "regex_check") -@external(javascript, "../gleam_stdlib.mjs", "regex_check") -fn do_check(regex: Regex, string: String) -> Bool - -/// Splits a string. -/// -/// ## Examples -/// -/// ```gleam -/// let assert Ok(re) = from_string(" *, *") -/// split(with: re, content: "foo,32, 4, 9 ,0") -/// // -> ["foo", "32", "4", "9", "0"] -/// ``` -/// -pub fn split(with regex: Regex, content string: String) -> List(String) { - do_split(regex, string) -} - -@external(erlang, "gleam_stdlib", "regex_split") -@external(javascript, "../gleam_stdlib.mjs", "regex_split") -fn do_split(regex: Regex, string: String) -> List(String) - -/// Collects all matches of the regular expression. -/// -/// ## Examples -/// -/// ```gleam -/// let assert Ok(re) = from_string("[oi]n a (\\w+)") -/// scan(with: re, content: "I am on a boat in a lake.") -/// // -> [ -/// // Match(content: "on a boat", submatches: [Some("boat")]), -/// // Match(content: "in a lake", submatches: [Some("lake")]), -/// // ] -/// ``` -/// -/// ```gleam -/// let assert Ok(re) = regex.from_string("([+|\\-])?(\\d+)(\\w+)?") -/// scan(with: re, content: "-36") -/// // -> [ -/// // Match(content: "-36", submatches: [Some("-"), Some("36")]) -/// // ] -/// -/// scan(with: re, content: "36") -/// // -> [ -/// // Match(content: "36", submatches: [None, Some("36")]) -/// // ] -/// ``` -/// -/// ```gleam -/// let assert Ok(re) = -/// regex.from_string("var\\s*(\\w+)\\s*(int|string)?\\s*=\\s*(.*)") -/// scan(with: re, content: "var age = 32") -/// // -> [ -/// // Match( -/// // content: "var age = 32", -/// // submatches: [Some("age"), None, Some("32")], -/// // ), -/// // ] -/// ``` -/// -/// ```gleam -/// let assert Ok(re) = regex.from_string("let (\\w+) = (\\w+)") -/// scan(with: re, content: "let age = 32") -/// // -> [ -/// // Match( -/// // content: "let age = 32", -/// // submatches: [Some("age"), Some("32")], -/// // ), -/// // ] -/// -/// scan(with: re, content: "const age = 32") -/// // -> [] -/// ``` -/// -pub fn scan(with regex: Regex, content string: String) -> List(Match) { - do_scan(regex, string) -} - -@external(erlang, "gleam_stdlib", "regex_scan") -@external(javascript, "../gleam_stdlib.mjs", "regex_scan") -fn do_scan(regex: Regex, string: String) -> List(Match) - -/// Creates a new `String` by replacing all substrings that match the regular -/// expression. -/// -/// ## Examples -/// -/// ```gleam -/// let assert Ok(re) = regex.from_string("^https://") -/// replace(each: re, in: "https://example.com", with: "www.") -/// // -> "www.example.com" -/// ``` -/// -/// ```gleam -/// let assert Ok(re) = regex.from_string("[, +-]") -/// replace(each: re, in: "a,b-c d+e", with: "/") -/// // -> "a/b/c/d/e" -/// ``` -@external(erlang, "gleam_stdlib", "regex_replace") -@external(javascript, "../gleam_stdlib.mjs", "regex_replace") -pub fn replace( - each pattern: Regex, - in string: String, - with substitute: String, -) -> String diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/result.gleam b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/result.gleam deleted file mode 100644 index 235c347a5f7..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/result.gleam +++ /dev/null @@ -1,486 +0,0 @@ -//// Result represents the result of something that may succeed or not. -//// `Ok` means it was successful, `Error` means it was not successful. - -import gleam/list - -/// Checks whether the result is an `Ok` value. -/// -/// ## Examples -/// -/// ```gleam -/// is_ok(Ok(1)) -/// // -> True -/// ``` -/// -/// ```gleam -/// is_ok(Error(Nil)) -/// // -> False -/// ``` -/// -pub fn is_ok(result: Result(a, e)) -> Bool { - case result { - Error(_) -> False - Ok(_) -> True - } -} - -/// Checks whether the result is an `Error` value. -/// -/// ## Examples -/// -/// ```gleam -/// is_error(Ok(1)) -/// // -> False -/// ``` -/// -/// ```gleam -/// is_error(Error(Nil)) -/// // -> True -/// ``` -/// -pub fn is_error(result: Result(a, e)) -> Bool { - case result { - Ok(_) -> False - Error(_) -> True - } -} - -/// Updates a value held within the `Ok` of a result by calling a given function -/// on it. -/// -/// If the result is an `Error` rather than `Ok` the function is not called and the -/// result stays the same. -/// -/// ## Examples -/// -/// ```gleam -/// map(over: Ok(1), with: fn(x) { x + 1 }) -/// // -> Ok(2) -/// ``` -/// -/// ```gleam -/// map(over: Error(1), with: fn(x) { x + 1 }) -/// // -> Error(1) -/// ``` -/// -pub fn map(over result: Result(a, e), with fun: fn(a) -> b) -> Result(b, e) { - case result { - Ok(x) -> Ok(fun(x)) - Error(e) -> Error(e) - } -} - -/// Updates a value held within the `Error` of a result by calling a given function -/// on it. -/// -/// If the result is `Ok` rather than `Error` the function is not called and the -/// result stays the same. -/// -/// ## Examples -/// -/// ```gleam -/// map_error(over: Error(1), with: fn(x) { x + 1 }) -/// // -> Error(2) -/// ``` -/// -/// ```gleam -/// map_error(over: Ok(1), with: fn(x) { x + 1 }) -/// // -> Ok(1) -/// ``` -/// -pub fn map_error( - over result: Result(a, e), - with fun: fn(e) -> f, -) -> Result(a, f) { - case result { - Ok(x) -> Ok(x) - Error(error) -> Error(fun(error)) - } -} - -/// Merges a nested `Result` into a single layer. -/// -/// ## Examples -/// -/// ```gleam -/// flatten(Ok(Ok(1))) -/// // -> Ok(1) -/// ``` -/// -/// ```gleam -/// flatten(Ok(Error(""))) -/// // -> Error("") -/// ``` -/// -/// ```gleam -/// flatten(Error(Nil)) -/// // -> Error(Nil) -/// ``` -/// -pub fn flatten(result: Result(Result(a, e), e)) -> Result(a, e) { - case result { - Ok(x) -> x - Error(error) -> Error(error) - } -} - -/// "Updates" an `Ok` result by passing its value to a function that yields a result, -/// and returning the yielded result. (This may "replace" the `Ok` with an `Error`.) -/// -/// If the input is an `Error` rather than an `Ok`, the function is not called and -/// the original `Error` is returned. -/// -/// This function is the equivalent of calling `map` followed by `flatten`, and -/// it is useful for chaining together multiple functions that may fail. -/// -/// ## Examples -/// -/// ```gleam -/// try(Ok(1), fn(x) { Ok(x + 1) }) -/// // -> Ok(2) -/// ``` -/// -/// ```gleam -/// try(Ok(1), fn(x) { Ok(#("a", x)) }) -/// // -> Ok(#("a", 1)) -/// ``` -/// -/// ```gleam -/// try(Ok(1), fn(_) { Error("Oh no") }) -/// // -> Error("Oh no") -/// ``` -/// -/// ```gleam -/// try(Error(Nil), fn(x) { Ok(x + 1) }) -/// // -> Error(Nil) -/// ``` -/// -pub fn try( - result: Result(a, e), - apply fun: fn(a) -> Result(b, e), -) -> Result(b, e) { - case result { - Ok(x) -> fun(x) - Error(e) -> Error(e) - } -} - -/// An alias for `try`. See the documentation for that function for more information. -/// -pub fn then( - result: Result(a, e), - apply fun: fn(a) -> Result(b, e), -) -> Result(b, e) { - try(result, fun) -} - -/// Extracts the `Ok` value from a result, returning a default value if the result -/// is an `Error`. -/// -/// ## Examples -/// -/// ```gleam -/// unwrap(Ok(1), 0) -/// // -> 1 -/// ``` -/// -/// ```gleam -/// unwrap(Error(""), 0) -/// // -> 0 -/// ``` -/// -pub fn unwrap(result: Result(a, e), or default: a) -> a { - case result { - Ok(v) -> v - Error(_) -> default - } -} - -/// Extracts the `Ok` value from a result, evaluating the default function if the result -/// is an `Error`. -/// -/// ## Examples -/// -/// ```gleam -/// lazy_unwrap(Ok(1), fn() { 0 }) -/// // -> 1 -/// ``` -/// -/// ```gleam -/// lazy_unwrap(Error(""), fn() { 0 }) -/// // -> 0 -/// ``` -/// -pub fn lazy_unwrap(result: Result(a, e), or default: fn() -> a) -> a { - case result { - Ok(v) -> v - Error(_) -> default() - } -} - -/// Extracts the `Error` value from a result, returning a default value if the result -/// is an `Ok`. -/// -/// ## Examples -/// -/// ```gleam -/// unwrap_error(Error(1), 0) -/// // -> 1 -/// ``` -/// -/// ```gleam -/// unwrap_error(Ok(""), 0) -/// // -> 0 -/// ``` -/// -pub fn unwrap_error(result: Result(a, e), or default: e) -> e { - case result { - Ok(_) -> default - Error(e) -> e - } -} - -/// Extracts the inner value from a result. Both the value and error must be of -/// the same type. -/// -/// ## Examples -/// -/// ```gleam -/// unwrap_both(Error(1)) -/// // -> 1 -/// ``` -/// -/// ```gleam -/// unwrap_both(Ok(2)) -/// // -> 2 -/// ``` -/// -pub fn unwrap_both(result: Result(a, a)) -> a { - case result { - Ok(a) -> a - Error(a) -> a - } -} - -/// Transforms any error into `Error(Nil)`. -/// -/// ## Examples -/// -/// ```gleam -/// nil_error(Error(1)) -/// // -> Error(Nil) -/// ``` -/// -/// ```gleam -/// nil_error(Ok(1)) -/// // -> Ok(1) -/// ``` -/// -pub fn nil_error(result: Result(a, e)) -> Result(a, Nil) { - map_error(result, fn(_) { Nil }) -} - -/// Returns the first value if it is `Ok`, otherwise returns the second value. -/// -/// ## Examples -/// -/// ```gleam -/// or(Ok(1), Ok(2)) -/// // -> Ok(1) -/// ``` -/// -/// ```gleam -/// or(Ok(1), Error("Error 2")) -/// // -> Ok(1) -/// ``` -/// -/// ```gleam -/// or(Error("Error 1"), Ok(2)) -/// // -> Ok(2) -/// ``` -/// -/// ```gleam -/// or(Error("Error 1"), Error("Error 2")) -/// // -> Error("Error 2") -/// ``` -/// -pub fn or(first: Result(a, e), second: Result(a, e)) -> Result(a, e) { - case first { - Ok(_) -> first - Error(_) -> second - } -} - -/// Returns the first value if it is `Ok`, otherwise evaluates the given function for a fallback value. -/// -/// If you need access to the initial error value, use `result.try_recover`. -/// -/// ## Examples -/// -/// ```gleam -/// lazy_or(Ok(1), fn() { Ok(2) }) -/// // -> Ok(1) -/// ``` -/// -/// ```gleam -/// lazy_or(Ok(1), fn() { Error("Error 2") }) -/// // -> Ok(1) -/// ``` -/// -/// ```gleam -/// lazy_or(Error("Error 1"), fn() { Ok(2) }) -/// // -> Ok(2) -/// ``` -/// -/// ```gleam -/// lazy_or(Error("Error 1"), fn() { Error("Error 2") }) -/// // -> Error("Error 2") -/// ``` -/// -pub fn lazy_or( - first: Result(a, e), - second: fn() -> Result(a, e), -) -> Result(a, e) { - case first { - Ok(_) -> first - Error(_) -> second() - } -} - -/// Combines a list of results into a single result. -/// If all elements in the list are `Ok` then returns an `Ok` holding the list of values. -/// If any element is `Error` then returns the first error. -/// -/// ## Examples -/// -/// ```gleam -/// all([Ok(1), Ok(2)]) -/// // -> Ok([1, 2]) -/// ``` -/// -/// ```gleam -/// all([Ok(1), Error("e")]) -/// // -> Error("e") -/// ``` -/// -pub fn all(results: List(Result(a, e))) -> Result(List(a), e) { - list.try_map(results, fn(x) { x }) -} - -/// Given a list of results, returns a pair where the first element is a list -/// of all the values inside `Ok` and the second element is a list with all the -/// values inside `Error`. The values in both lists appear in reverse order with -/// respect to their position in the original list of results. -/// -/// ## Examples -/// -/// ```gleam -/// partition([Ok(1), Error("a"), Error("b"), Ok(2)]) -/// // -> #([2, 1], ["b", "a"]) -/// ``` -/// -pub fn partition(results: List(Result(a, e))) -> #(List(a), List(e)) { - do_partition(results, [], []) -} - -fn do_partition(results: List(Result(a, e)), oks: List(a), errors: List(e)) { - case results { - [] -> #(oks, errors) - [Ok(a), ..rest] -> do_partition(rest, [a, ..oks], errors) - [Error(e), ..rest] -> do_partition(rest, oks, [e, ..errors]) - } -} - -/// Replace the value within a result -/// -/// ## Examples -/// -/// ```gleam -/// replace(Ok(1), Nil) -/// // -> Ok(Nil) -/// ``` -/// -/// ```gleam -/// replace(Error(1), Nil) -/// // -> Error(1) -/// ``` -/// -pub fn replace(result: Result(a, e), value: b) -> Result(b, e) { - case result { - Ok(_) -> Ok(value) - Error(error) -> Error(error) - } -} - -/// Replace the error within a result -/// -/// ## Examples -/// -/// ```gleam -/// replace_error(Error(1), Nil) -/// // -> Error(Nil) -/// ``` -/// -/// ```gleam -/// replace_error(Ok(1), Nil) -/// // -> Ok(1) -/// ``` -/// -pub fn replace_error(result: Result(a, e), error: f) -> Result(a, f) { - case result { - Ok(x) -> Ok(x) - Error(_) -> Error(error) - } -} - -/// Given a list of results, returns only the values inside `Ok`. -/// -/// ## Examples -/// -/// ```gleam -/// values([Ok(1), Error("a"), Ok(3)]) -/// // -> [1, 3] -/// ``` -/// -pub fn values(results: List(Result(a, e))) -> List(a) { - list.filter_map(results, fn(r) { r }) -} - -/// Updates a value held within the `Error` of a result by calling a given function -/// on it, where the given function also returns a result. The two results are -/// then merged together into one result. -/// -/// If the result is an `Ok` rather than `Error` the function is not called and the -/// result stays the same. -/// -/// This function is useful for chaining together computations that may fail -/// and trying to recover from possible errors. -/// -/// If you do not need access to the initial error value, use `result.lazy_or`. -/// -/// ## Examples -/// -/// ```gleam -/// Ok(1) |> try_recover(with: fn(_) { Error("failed to recover") }) -/// // -> Ok(1) -/// ``` -/// -/// ```gleam -/// Error(1) |> try_recover(with: fn(error) { Ok(error + 1) }) -/// // -> Ok(2) -/// ``` -/// -/// ```gleam -/// Error(1) |> try_recover(with: fn(error) { Error("failed to recover") }) -/// // -> Error("failed to recover") -/// ``` -/// -pub fn try_recover( - result: Result(a, e), - with fun: fn(e) -> Result(a, f), -) -> Result(a, f) { - case result { - Ok(value) -> Ok(value) - Error(error) -> fun(error) - } -} diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/set.gleam b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/set.gleam deleted file mode 100644 index f70c716002b..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/set.gleam +++ /dev/null @@ -1,407 +0,0 @@ -import gleam/dict.{type Dict} -import gleam/list -import gleam/result - -// A list is used as the dict value as an empty list has the smallest -// representation in Erlang's binary format -@target(erlang) -type Token = - List(Nil) - -@target(erlang) -const token = [] - -@target(javascript) -type Token = - Nil - -@target(javascript) -const token = Nil - -/// A set is a collection of unique members of the same type. -/// -/// It is implemented using the `gleam/dict` module, so inserts and lookups have -/// logarithmic time complexity. -/// -pub opaque type Set(member) { - Set(dict: Dict(member, Token)) -} - -/// Creates a new empty set. -/// -pub fn new() -> Set(member) { - Set(dict.new()) -} - -/// Gets the number of members in a set. -/// -/// This function runs in constant time. -/// -/// ## Examples -/// -/// ```gleam -/// new() -/// |> insert(1) -/// |> insert(2) -/// |> size -/// // -> 2 -/// ``` -/// -pub fn size(set: Set(member)) -> Int { - dict.size(set.dict) -} - -/// Determines whether or not the set is empty. -/// -/// ## Examples -/// -/// ```gleam -/// new() |> is_empty -/// // -> True -/// ``` -/// -/// ```gleam -/// new() |> insert(1) |> is_empty -/// // -> False -/// ``` -/// -pub fn is_empty(set: Set(member)) -> Bool { - set == new() -} - -/// Inserts an member into the set. -/// -/// This function runs in logarithmic time. -/// -/// ## Examples -/// -/// ```gleam -/// new() -/// |> insert(1) -/// |> insert(2) -/// |> size -/// // -> 2 -/// ``` -/// -pub fn insert(into set: Set(member), this member: member) -> Set(member) { - Set(dict: dict.insert(set.dict, member, token)) -} - -/// Checks whether a set contains a given member. -/// -/// This function runs in logarithmic time. -/// -/// ## Examples -/// -/// ```gleam -/// new() -/// |> insert(2) -/// |> contains(2) -/// // -> True -/// ``` -/// -/// ```gleam -/// new() -/// |> insert(2) -/// |> contains(1) -/// // -> False -/// ``` -/// -pub fn contains(in set: Set(member), this member: member) -> Bool { - set.dict - |> dict.get(member) - |> result.is_ok -} - -/// Removes a member from a set. If the set does not contain the member then -/// the set is returned unchanged. -/// -/// This function runs in logarithmic time. -/// -/// ## Examples -/// -/// ```gleam -/// new() -/// |> insert(2) -/// |> delete(2) -/// |> contains(1) -/// // -> False -/// ``` -/// -pub fn delete(from set: Set(member), this member: member) -> Set(member) { - Set(dict: dict.delete(set.dict, member)) -} - -/// Converts the set into a list of the contained members. -/// -/// The list has no specific ordering, any unintentional ordering may change in -/// future versions of Gleam or Erlang. -/// -/// This function runs in linear time. -/// -/// ## Examples -/// -/// ```gleam -/// new() |> insert(2) |> to_list -/// // -> [2] -/// ``` -/// -pub fn to_list(set: Set(member)) -> List(member) { - dict.keys(set.dict) -} - -/// Creates a new set of the members in a given list. -/// -/// This function runs in loglinear time. -/// -/// ## Examples -/// -/// ```gleam -/// import gleam/int -/// import gleam/list -/// -/// [1, 1, 2, 4, 3, 2] |> from_list |> to_list |> list.sort(by: int.compare) -/// // -> [1, 2, 3, 4] -/// ``` -/// -pub fn from_list(members: List(member)) -> Set(member) { - let dict = - list.fold(over: members, from: dict.new(), with: fn(m, k) { - dict.insert(m, k, token) - }) - Set(dict) -} - -/// Combines all entries into a single value by calling a given function on each -/// one. -/// -/// Sets are not ordered so the values are not returned in any specific order. -/// Do not write code that relies on the order entries are used by this -/// function as it may change in later versions of Gleam or Erlang. -/// -/// # Examples -/// -/// ```gleam -/// from_list([1, 3, 9]) -/// |> fold(0, fn(accumulator, member) { accumulator + member }) -/// // -> 13 -/// ``` -/// -pub fn fold( - over set: Set(member), - from initial: acc, - with reducer: fn(acc, member) -> acc, -) -> acc { - dict.fold(over: set.dict, from: initial, with: fn(a, k, _) { reducer(a, k) }) -} - -/// Creates a new set from an existing set, minus any members that a given -/// function returns `False` for. -/// -/// This function runs in loglinear time. -/// -/// ## Examples -/// -/// ```gleam -/// import gleam/int -/// -/// from_list([1, 4, 6, 3, 675, 44, 67]) -/// |> filter(keeping: int.is_even) -/// |> to_list -/// // -> [4, 6, 44] -/// ``` -/// -pub fn filter( - in set: Set(member), - keeping predicate: fn(member) -> Bool, -) -> Set(member) { - Set(dict.filter(in: set.dict, keeping: fn(m, _) { predicate(m) })) -} - -/// Creates a new set from a given set with the result of applying the given -/// function to each member. -/// -/// ## Examples -/// -/// ```gleam -/// from_list([1, 2, 3, 4]) -/// |> map(with: fn(x) { x * 2 }) -/// |> to_list -/// // -> [2, 4, 6, 8] -/// ``` -pub fn map(set: Set(member), with fun: fn(member) -> mapped) -> Set(mapped) { - fold(over: set, from: new(), with: fn(acc, member) { - insert(acc, fun(member)) - }) -} - -/// Creates a new set from a given set with all the same entries except any -/// entry found on the given list. -/// -/// ## Examples -/// -/// ```gleam -/// from_list([1, 2, 3, 4]) -/// |> drop([1, 3]) -/// |> to_list -/// // -> [2, 4] -/// ``` -pub fn drop(from set: Set(member), drop disallowed: List(member)) -> Set(member) { - list.fold(over: disallowed, from: set, with: delete) -} - -/// Creates a new set from a given set, only including any members which are in -/// a given list. -/// -/// This function runs in loglinear time. -/// -/// ## Examples -/// -/// ```gleam -/// from_list([1, 2, 3]) -/// |> take([1, 3, 5]) -/// |> to_list -/// // -> [1, 3] -/// ``` -/// -pub fn take(from set: Set(member), keeping desired: List(member)) -> Set(member) { - Set(dict.take(from: set.dict, keeping: desired)) -} - -fn order(first: Set(member), second: Set(member)) -> #(Set(member), Set(member)) { - case dict.size(first.dict) > dict.size(second.dict) { - True -> #(first, second) - False -> #(second, first) - } -} - -/// Creates a new set that contains all members of both given sets. -/// -/// This function runs in loglinear time. -/// -/// ## Examples -/// -/// ```gleam -/// union(from_list([1, 2]), from_list([2, 3])) |> to_list -/// // -> [1, 2, 3] -/// ``` -/// -pub fn union(of first: Set(member), and second: Set(member)) -> Set(member) { - let #(larger, smaller) = order(first, second) - fold(over: smaller, from: larger, with: insert) -} - -/// Creates a new set that contains members that are present in both given sets. -/// -/// This function runs in loglinear time. -/// -/// ## Examples -/// -/// ```gleam -/// intersection(from_list([1, 2]), from_list([2, 3])) |> to_list -/// // -> [2] -/// ``` -/// -pub fn intersection( - of first: Set(member), - and second: Set(member), -) -> Set(member) { - let #(larger, smaller) = order(first, second) - take(from: larger, keeping: to_list(smaller)) -} - -/// Creates a new set that contains members that are present in the first set -/// but not the second. -/// -/// ## Examples -/// -/// ```gleam -/// difference(from_list([1, 2]), from_list([2, 3, 4])) |> to_list -/// // -> [1] -/// ``` -/// -pub fn difference( - from first: Set(member), - minus second: Set(member), -) -> Set(member) { - drop(from: first, drop: to_list(second)) -} - -/// Determines if a set is fully contained by another. -/// -/// ## Examples -/// -/// ```gleam -/// is_subset(from_list([1]), from_list([1, 2])) -/// // -> True -/// ``` -/// -/// ```gleam -/// is_subset(from_list([1, 2, 3]), from_list([3, 4, 5])) -/// // -> False -/// ``` -/// -pub fn is_subset(first: Set(member), of second: Set(member)) -> Bool { - intersection(of: first, and: second) == first -} - -/// Determines if two sets contain no common members -/// -/// ## Examples -/// -/// ```gleam -/// is_disjoint(from_list([1, 2, 3]), from_list([4, 5, 6])) -/// // -> True -/// ``` -/// -/// ```gleam -/// is_disjoint(from_list([1, 2, 3]), from_list([3, 4, 5])) -/// // -> False -/// ``` -/// -pub fn is_disjoint(first: Set(member), from second: Set(member)) -> Bool { - intersection(of: first, and: second) == new() -} - -/// Creates a new set that contains members that are present in either set, but -/// not both. -/// -/// ```gleam -/// symmetric_difference(from_list([1, 2, 3]), from_list([3, 4])) |> to_list -/// // -> [1, 2, 4] -/// ``` -/// -pub fn symmetric_difference( - of first: Set(member), - and second: Set(member), -) -> Set(member) { - difference( - from: union(of: first, and: second), - minus: intersection(of: first, and: second), - ) -} - -/// Calls a function for each member in a set, discarding the return -/// value. -/// -/// Useful for producing a side effect for every item of a set. -/// -/// ```gleam -/// let set = from_list(["apple", "banana", "cherry"]) -/// -/// each(set, io.println) -/// // -> Nil -/// // apple -/// // banana -/// // cherry -/// ``` -/// -/// The order of elements in the iteration is an implementation detail that -/// should not be relied upon. -/// -pub fn each(set: Set(member), fun: fn(member) -> a) -> Nil { - fold(set, Nil, fn(nil, member) { - fun(member) - nil - }) -} diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam deleted file mode 100644 index 0f073b95475..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string.gleam +++ /dev/null @@ -1,880 +0,0 @@ -//// Strings in Gleam are UTF-8 binaries. They can be written in your code as -//// text surrounded by `"double quotes"`. - -import gleam/list -import gleam/option.{type Option, None, Some} -import gleam/order -import gleam/string_builder.{type StringBuilder} - -/// Determines if a `String` is empty. -/// -/// ## Examples -/// -/// ```gleam -/// is_empty("") -/// // -> True -/// ``` -/// -/// ```gleam -/// is_empty("the world") -/// // -> False -/// ``` -/// -pub fn is_empty(str: String) -> Bool { - str == "" -} - -/// Gets the number of grapheme clusters in a given `String`. -/// -/// This function has to iterate across the whole string to count the number of -/// graphemes, so it runs in linear time. -/// -/// ## Examples -/// -/// ```gleam -/// length("Gleam") -/// // -> 5 -/// ``` -/// -/// ```gleam -/// length("ß↑e̊") -/// // -> 3 -/// ``` -/// -/// ```gleam -/// length("") -/// // -> 0 -/// ``` -/// -pub fn length(string: String) -> Int { - do_length(string) -} - -@external(erlang, "string", "length") -@external(javascript, "../gleam_stdlib.mjs", "string_length") -fn do_length(a: String) -> Int - -/// Reverses a `String`. -/// -/// This function has to iterate across the whole `String` so it runs in linear -/// time. -/// -/// ## Examples -/// -/// ```gleam -/// reverse("stressed") -/// // -> "desserts" -/// ``` -/// -pub fn reverse(string: String) -> String { - do_reverse(string) -} - -fn do_reverse(string: String) -> String { - string - |> string_builder.from_string - |> string_builder.reverse - |> string_builder.to_string -} - -/// Creates a new `String` by replacing all occurrences of a given substring. -/// -/// ## Examples -/// -/// ```gleam -/// replace("www.example.com", each: ".", with: "-") -/// // -> "www-example-com" -/// ``` -/// -/// ```gleam -/// replace("a,b,c,d,e", each: ",", with: "/") -/// // -> "a/b/c/d/e" -/// ``` -/// -pub fn replace( - in string: String, - each pattern: String, - with substitute: String, -) -> String { - string - |> string_builder.from_string - |> string_builder.replace(each: pattern, with: substitute) - |> string_builder.to_string -} - -/// Creates a new `String` with all the graphemes in the input `String` converted to -/// lowercase. -/// -/// Useful for case-insensitive comparisons. -/// -/// ## Examples -/// -/// ```gleam -/// lowercase("X-FILES") -/// // -> "x-files" -/// ``` -/// -pub fn lowercase(string: String) -> String { - do_lowercase(string) -} - -@external(erlang, "string", "lowercase") -@external(javascript, "../gleam_stdlib.mjs", "lowercase") -fn do_lowercase(a: String) -> String - -/// Creates a new `String` with all the graphemes in the input `String` converted to -/// uppercase. -/// -/// Useful for case-insensitive comparisons and VIRTUAL YELLING. -/// -/// ## Examples -/// -/// ```gleam -/// uppercase("skinner") -/// // -> "SKINNER" -/// ``` -/// -pub fn uppercase(string: String) -> String { - do_uppercase(string) -} - -@external(erlang, "string", "uppercase") -@external(javascript, "../gleam_stdlib.mjs", "uppercase") -fn do_uppercase(a: String) -> String - -/// Compares two `String`s to see which is "larger" by comparing their graphemes. -/// -/// This does not compare the size or length of the given `String`s. -/// -/// ## Examples -/// -/// ```gleam -/// compare("Anthony", "Anthony") -/// // -> order.Eq -/// ``` -/// -/// ```gleam -/// compare("A", "B") -/// // -> order.Lt -/// ``` -/// -pub fn compare(a: String, b: String) -> order.Order { - case a == b { - True -> order.Eq - _ -> - case less_than(a, b) { - True -> order.Lt - _ -> order.Gt - } - } -} - -@external(erlang, "gleam_stdlib", "less_than") -@external(javascript, "../gleam_stdlib.mjs", "less_than") -fn less_than(a: String, b: String) -> Bool - -/// Takes a substring given a start grapheme index and a length. Negative indexes -/// are taken starting from the *end* of the list. -/// -/// ## Examples -/// -/// ```gleam -/// slice(from: "gleam", at_index: 1, length: 2) -/// // -> "le" -/// ``` -/// -/// ```gleam -/// slice(from: "gleam", at_index: 1, length: 10) -/// // -> "leam" -/// ``` -/// -/// ```gleam -/// slice(from: "gleam", at_index: 10, length: 3) -/// // -> "" -/// ``` -/// -/// ```gleam -/// slice(from: "gleam", at_index: -2, length: 2) -/// // -> "am" -/// ``` -/// -/// ```gleam -/// slice(from: "gleam", at_index: -12, length: 2) -/// // -> "" -/// ``` -/// -pub fn slice(from string: String, at_index idx: Int, length len: Int) -> String { - case len < 0 { - True -> "" - False -> - case idx < 0 { - True -> { - let translated_idx = length(string) + idx - case translated_idx < 0 { - True -> "" - False -> do_slice(string, translated_idx, len) - } - } - False -> do_slice(string, idx, len) - } - } -} - -@external(erlang, "gleam_stdlib", "slice") -@external(javascript, "../gleam_stdlib.mjs", "string_slice") -fn do_slice(string: String, idx: Int, len: Int) -> String - -/// Drops contents of the first `String` that occur before the second `String`. -/// If the `from` string does not contain the `before` string, `from` is returned unchanged. -/// -/// ## Examples -/// -/// ```gleam -/// crop(from: "The Lone Gunmen", before: "Lone") -/// // -> "Lone Gunmen" -/// ``` -/// -@external(erlang, "gleam_stdlib", "crop_string") -@external(javascript, "../gleam_stdlib.mjs", "crop_string") -pub fn crop(from string: String, before substring: String) -> String - -/// Drops *n* graphemes from the left side of a `String`. -/// -/// ## Examples -/// -/// ```gleam -/// drop_left(from: "The Lone Gunmen", up_to: 2) -/// // -> "e Lone Gunmen" -/// ``` -/// -pub fn drop_left(from string: String, up_to num_graphemes: Int) -> String { - case num_graphemes < 0 { - True -> string - False -> slice(string, num_graphemes, length(string) - num_graphemes) - } -} - -/// Drops *n* graphemes from the right side of a `String`. -/// -/// ## Examples -/// -/// ```gleam -/// drop_right(from: "Cigarette Smoking Man", up_to: 2) -/// // -> "Cigarette Smoking M" -/// ``` -/// -pub fn drop_right(from string: String, up_to num_graphemes: Int) -> String { - case num_graphemes < 0 { - True -> string - False -> slice(string, 0, length(string) - num_graphemes) - } -} - -/// Checks if the first `String` contains the second. -/// -/// ## Examples -/// -/// ```gleam -/// contains(does: "theory", contain: "ory") -/// // -> True -/// ``` -/// -/// ```gleam -/// contains(does: "theory", contain: "the") -/// // -> True -/// ``` -/// -/// ```gleam -/// contains(does: "theory", contain: "THE") -/// // -> False -/// ``` -/// -@external(erlang, "gleam_stdlib", "contains_string") -@external(javascript, "../gleam_stdlib.mjs", "contains_string") -pub fn contains(does haystack: String, contain needle: String) -> Bool - -/// Checks whether the first `String` starts with the second one. -/// -/// ## Examples -/// -/// ```gleam -/// starts_with("theory", "ory") -/// // -> False -/// ``` -/// -pub fn starts_with(string: String, prefix: String) -> Bool { - do_starts_with(string, prefix) -} - -@external(erlang, "gleam_stdlib", "string_starts_with") -@external(javascript, "../gleam_stdlib.mjs", "starts_with") -fn do_starts_with(a: String, b: String) -> Bool - -/// Checks whether the first `String` ends with the second one. -/// -/// ## Examples -/// -/// ```gleam -/// ends_with("theory", "ory") -/// // -> True -/// ``` -/// -pub fn ends_with(string: String, suffix: String) -> Bool { - do_ends_with(string, suffix) -} - -@external(erlang, "gleam_stdlib", "string_ends_with") -@external(javascript, "../gleam_stdlib.mjs", "ends_with") -fn do_ends_with(a: String, b: String) -> Bool - -/// Creates a list of `String`s by splitting a given string on a given substring. -/// -/// ## Examples -/// -/// ```gleam -/// split("home/gleam/desktop/", on: "/") -/// // -> ["home", "gleam", "desktop", ""] -/// ``` -/// -pub fn split(x: String, on substring: String) -> List(String) { - case substring { - "" -> to_graphemes(x) - _ -> - x - |> string_builder.from_string - |> string_builder.split(on: substring) - |> list.map(with: string_builder.to_string) - } -} - -/// Splits a `String` a single time on the given substring. -/// -/// Returns an `Error` if substring not present. -/// -/// ## Examples -/// -/// ```gleam -/// split_once("home/gleam/desktop/", on: "/") -/// // -> Ok(#("home", "gleam/desktop/")) -/// ``` -/// -/// ```gleam -/// split_once("home/gleam/desktop/", on: "?") -/// // -> Error(Nil) -/// ``` -/// -pub fn split_once( - string: String, - on substring: String, -) -> Result(#(String, String), Nil) { - do_split_once(string, substring) -} - -@external(javascript, "../gleam_stdlib.mjs", "split_once") -fn do_split_once( - string: String, - substring: String, -) -> Result(#(String, String), Nil) { - case erl_split(string, substring) { - [first, rest] -> Ok(#(first, rest)) - _ -> Error(Nil) - } -} - -@external(erlang, "string", "split") -fn erl_split(a: String, b: String) -> List(String) - -/// Creates a new `String` by joining two `String`s together. -/// -/// This function copies both `String`s and runs in linear time. If you find -/// yourself joining `String`s frequently consider using the [`string_builder`](../gleam/string_builder.html) -/// module as it can append `String`s much faster! -/// -/// ## Examples -/// -/// ```gleam -/// append(to: "butter", suffix: "fly") -/// // -> "butterfly" -/// ``` -/// -pub fn append(to first: String, suffix second: String) -> String { - first - |> string_builder.from_string - |> string_builder.append(second) - |> string_builder.to_string -} - -/// Creates a new `String` by joining many `String`s together. -/// -/// This function copies both `String`s and runs in linear time. If you find -/// yourself joining `String`s frequently consider using the [`string_builder`](../gleam/string_builder.html) -/// module as it can append `String`s much faster! -/// -/// ## Examples -/// -/// ```gleam -/// concat(["never", "the", "less"]) -/// // -> "nevertheless" -/// ``` -/// -pub fn concat(strings: List(String)) -> String { - strings - |> string_builder.from_strings - |> string_builder.to_string -} - -/// Creates a new `String` by repeating a `String` a given number of times. -/// -/// This function runs in linear time. -/// -/// ## Examples -/// -/// ```gleam -/// repeat("ha", times: 3) -/// // -> "hahaha" -/// ``` -/// -pub fn repeat(string: String, times times: Int) -> String { - do_repeat(string, times, "") -} - -fn do_repeat(string: String, times: Int, acc: String) -> String { - case times <= 0 { - True -> acc - False -> do_repeat(string, times - 1, acc <> string) - } -} - -/// Joins many `String`s together with a given separator. -/// -/// This function runs in linear time. -/// -/// ## Examples -/// -/// ```gleam -/// join(["home","evan","Desktop"], with: "/") -/// // -> "home/evan/Desktop" -/// ``` -/// -pub fn join(strings: List(String), with separator: String) -> String { - do_join(strings, separator) -} - -@external(javascript, "../gleam_stdlib.mjs", "join") -fn do_join(strings: List(String), separator: String) -> String { - strings - |> list.intersperse(with: separator) - |> concat -} - -/// Pads a `String` on the left until it has at least given number of graphemes. -/// -/// ## Examples -/// -/// ```gleam -/// pad_left("121", to: 5, with: ".") -/// // -> "..121" -/// ``` -/// -/// ```gleam -/// pad_left("121", to: 3, with: ".") -/// // -> "121" -/// ``` -/// -/// ```gleam -/// pad_left("121", to: 2, with: ".") -/// // -> "121" -/// ``` -/// -pub fn pad_left( - string: String, - to desired_length: Int, - with pad_string: String, -) -> String { - let current_length = length(string) - let to_pad_length = desired_length - current_length - - case to_pad_length <= 0 { - True -> string - False -> padding(to_pad_length, pad_string) <> string - } -} - -/// Pads a `String` on the right until it has a given length. -/// -/// ## Examples -/// -/// ```gleam -/// pad_right("123", to: 5, with: ".") -/// // -> "123.." -/// ``` -/// -/// ```gleam -/// pad_right("123", to: 3, with: ".") -/// // -> "123" -/// ``` -/// -/// ```gleam -/// pad_right("123", to: 2, with: ".") -/// // -> "123" -/// ``` -/// -pub fn pad_right( - string: String, - to desired_length: Int, - with pad_string: String, -) -> String { - let current_length = length(string) - let to_pad_length = desired_length - current_length - - case to_pad_length <= 0 { - True -> string - False -> string <> padding(to_pad_length, pad_string) - } -} - -fn padding(size: Int, pad_string: String) -> String { - let pad_string_length = length(pad_string) - let num_pads = size / pad_string_length - let extra = size % pad_string_length - - repeat(pad_string, num_pads) <> slice(pad_string, 0, extra) -} - -/// Removes whitespace on both sides of a `String`. -/// -/// ## Examples -/// -/// ```gleam -/// trim(" hats \n") -/// // -> "hats" -/// ``` -/// -pub fn trim(string: String) -> String { - do_trim(string) -} - -@external(javascript, "../gleam_stdlib.mjs", "trim") -fn do_trim(string: String) -> String { - erl_trim(string, Both) -} - -@external(erlang, "string", "trim") -fn erl_trim(a: String, b: Direction) -> String - -type Direction { - Leading - Trailing - Both -} - -/// Removes whitespace on the left of a `String`. -/// -/// ## Examples -/// -/// ```gleam -/// trim_left(" hats \n") -/// // -> "hats \n" -/// ``` -/// -pub fn trim_left(string: String) -> String { - do_trim_left(string) -} - -@external(javascript, "../gleam_stdlib.mjs", "trim_left") -fn do_trim_left(string: String) -> String { - erl_trim(string, Leading) -} - -/// Removes whitespace on the right of a `String`. -/// -/// ## Examples -/// -/// ```gleam -/// trim_right(" hats \n") -/// // -> " hats" -/// ``` -/// -pub fn trim_right(string: String) -> String { - do_trim_right(string) -} - -@external(javascript, "../gleam_stdlib.mjs", "trim_right") -fn do_trim_right(string: String) -> String { - erl_trim(string, Trailing) -} - -/// Splits a non-empty `String` into its first element (head) and rest (tail). -/// This lets you pattern match on `String`s exactly as you would with lists. -/// -/// Note on JavaScript using the function to iterate over a string will likely -/// be slower than using `to_graphemes` due to string slicing being more -/// expensive on JavaScript than Erlang. -/// -/// ## Examples -/// -/// ```gleam -/// pop_grapheme("gleam") -/// // -> Ok(#("g", "leam")) -/// ``` -/// -/// ```gleam -/// pop_grapheme("") -/// // -> Error(Nil) -/// ``` -/// -pub fn pop_grapheme(string: String) -> Result(#(String, String), Nil) { - do_pop_grapheme(string) -} - -@external(erlang, "gleam_stdlib", "string_pop_grapheme") -@external(javascript, "../gleam_stdlib.mjs", "pop_grapheme") -fn do_pop_grapheme(string string: String) -> Result(#(String, String), Nil) - -/// Converts a `String` to a list of -/// [graphemes](https://en.wikipedia.org/wiki/Grapheme). -/// -/// ```gleam -/// to_graphemes("abc") -/// // -> ["a", "b", "c"] -/// ``` -/// -@external(javascript, "../gleam_stdlib.mjs", "graphemes") -pub fn to_graphemes(string: String) -> List(String) { - do_to_graphemes(string, []) - |> list.reverse -} - -fn do_to_graphemes(string: String, acc: List(String)) -> List(String) { - case pop_grapheme(string) { - Ok(#(grapheme, rest)) -> do_to_graphemes(rest, [grapheme, ..acc]) - _ -> acc - } -} - -@external(erlang, "gleam_stdlib", "identity") -@external(javascript, "../gleam_stdlib.mjs", "codepoint") -fn unsafe_int_to_utf_codepoint(a: Int) -> UtfCodepoint - -/// Converts a `String` to a `List` of `UtfCodepoint`. -/// -/// See and -/// for an -/// explanation on code points. -/// -/// ## Examples -/// -/// ```gleam -/// "a" |> to_utf_codepoints -/// // -> [UtfCodepoint(97)] -/// ``` -/// -/// ```gleam -/// // Semantically the same as: -/// // ["🏳", "️", "‍", "🌈"] or: -/// // [waving_white_flag, variant_selector_16, zero_width_joiner, rainbow] -/// "🏳️‍🌈" |> to_utf_codepoints -/// // -> [ -/// // UtfCodepoint(127987), -/// // UtfCodepoint(65039), -/// // UtfCodepoint(8205), -/// // UtfCodepoint(127752), -/// // ] -/// ``` -/// -pub fn to_utf_codepoints(string: String) -> List(UtfCodepoint) { - do_to_utf_codepoints(string) -} - -@target(erlang) -fn do_to_utf_codepoints(string: String) -> List(UtfCodepoint) { - do_to_utf_codepoints_impl(<>, []) - |> list.reverse -} - -@target(erlang) -fn do_to_utf_codepoints_impl( - bit_array: BitArray, - acc: List(UtfCodepoint), -) -> List(UtfCodepoint) { - case bit_array { - <> -> - do_to_utf_codepoints_impl(rest, [first, ..acc]) - _ -> acc - } -} - -@target(javascript) -fn do_to_utf_codepoints(string: String) -> List(UtfCodepoint) { - string - |> string_to_codepoint_integer_list - |> list.map(unsafe_int_to_utf_codepoint) -} - -@target(javascript) -@external(javascript, "../gleam_stdlib.mjs", "string_to_codepoint_integer_list") -fn string_to_codepoint_integer_list(string: String) -> List(Int) - -/// Converts a `List` of `UtfCodepoint`s to a `String`. -/// -/// See and -/// for an -/// explanation on code points. -/// -/// ## Examples -/// -/// ```gleam -/// let assert Ok(a) = utf_codepoint(97) -/// let assert Ok(b) = utf_codepoint(98) -/// let assert Ok(c) = utf_codepoint(99) -/// from_utf_codepoints([a, b, c]) -/// // -> "abc" -/// ``` -/// -@external(erlang, "gleam_stdlib", "utf_codepoint_list_to_string") -@external(javascript, "../gleam_stdlib.mjs", "utf_codepoint_list_to_string") -pub fn from_utf_codepoints(utf_codepoints: List(UtfCodepoint)) -> String - -/// Converts an integer to a `UtfCodepoint`. -/// -/// Returns an `Error` if the integer does not represent a valid UTF codepoint. -/// -pub fn utf_codepoint(value: Int) -> Result(UtfCodepoint, Nil) { - case value { - i if i > 1_114_111 -> Error(Nil) - 65_534 | 65_535 -> Error(Nil) - i if i >= 55_296 && i <= 57_343 -> Error(Nil) - i -> Ok(unsafe_int_to_utf_codepoint(i)) - } -} - -/// Converts an UtfCodepoint to its ordinal code point value. -/// -/// ## Examples -/// -/// ```gleam -/// let assert [utf_codepoint, ..] = to_utf_codepoints("💜") -/// utf_codepoint_to_int(utf_codepoint) -/// // -> 128156 -/// ``` -/// -pub fn utf_codepoint_to_int(cp: UtfCodepoint) -> Int { - do_utf_codepoint_to_int(cp) -} - -@external(erlang, "gleam_stdlib", "identity") -@external(javascript, "../gleam_stdlib.mjs", "utf_codepoint_to_int") -fn do_utf_codepoint_to_int(cp cp: UtfCodepoint) -> Int - -/// Converts a `String` into `Option(String)` where an empty `String` becomes -/// `None`. -/// -/// ## Examples -/// -/// ```gleam -/// to_option("") -/// // -> None -/// ``` -/// -/// ```gleam -/// to_option("hats") -/// // -> Some("hats") -/// ``` -/// -pub fn to_option(string: String) -> Option(String) { - case string { - "" -> None - _ -> Some(string) - } -} - -/// Returns the first grapheme cluster in a given `String` and wraps it in a -/// `Result(String, Nil)`. If the `String` is empty, it returns `Error(Nil)`. -/// Otherwise, it returns `Ok(String)`. -/// -/// ## Examples -/// -/// ```gleam -/// first("") -/// // -> Error(Nil) -/// ``` -/// -/// ```gleam -/// first("icecream") -/// // -> Ok("i") -/// ``` -/// -pub fn first(string: String) -> Result(String, Nil) { - case pop_grapheme(string) { - Ok(#(first, _)) -> Ok(first) - Error(e) -> Error(e) - } -} - -/// Returns the last grapheme cluster in a given `String` and wraps it in a -/// `Result(String, Nil)`. If the `String` is empty, it returns `Error(Nil)`. -/// Otherwise, it returns `Ok(String)`. -/// -/// ## Examples -/// -/// ```gleam -/// last("") -/// // -> Error(Nil) -/// ``` -/// -/// ```gleam -/// last("icecream") -/// // -> Ok("m") -/// ``` -/// -pub fn last(string: String) -> Result(String, Nil) { - case pop_grapheme(string) { - Ok(#(first, "")) -> Ok(first) - Ok(#(_, rest)) -> Ok(slice(rest, -1, 1)) - Error(e) -> Error(e) - } -} - -/// Creates a new `String` with the first grapheme in the input `String` -/// converted to uppercase and the remaining graphemes to lowercase. -/// -/// ## Examples -/// -/// ```gleam -/// capitalise("mamouna") -/// // -> "Mamouna" -/// ``` -/// -pub fn capitalise(string: String) -> String { - case pop_grapheme(string) { - Ok(#(first, rest)) -> append(to: uppercase(first), suffix: lowercase(rest)) - _ -> "" - } -} - -/// Returns a `String` representation of a term in Gleam syntax. -/// -pub fn inspect(term: anything) -> String { - do_inspect(term) - |> string_builder.to_string -} - -@external(erlang, "gleam_stdlib", "inspect") -@external(javascript, "../gleam_stdlib.mjs", "inspect") -fn do_inspect(term: anything) -> StringBuilder - -/// Returns the number of bytes in a `String`. -/// -/// This function runs in constant time on Erlang and in linear time on -/// JavaScript. -/// -/// ## Examples -/// -/// ```gleam -/// byte_size("🏳️‍⚧️🏳️‍🌈👩🏾‍❤️‍👨🏻") -/// // -> 58 -/// ``` -/// -@external(erlang, "erlang", "byte_size") -@external(javascript, "../gleam_stdlib.mjs", "byte_size") -pub fn byte_size(string: String) -> Int diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string_builder.gleam b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string_builder.gleam deleted file mode 100644 index 8cfd2ed1ecb..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/string_builder.gleam +++ /dev/null @@ -1,253 +0,0 @@ -import gleam/list - -/// `StringBuilder` is a type used for efficiently building text content to be -/// written to a file or a socket. Internally it is represented as tree so to -/// append or prepend to a string builder is a constant time operation that -/// allocates a new node in the tree without copying any of the content. When -/// writing to an output stream the tree is traversed and the content is sent -/// directly rather than copying it into a single buffer beforehand. -/// -/// On Erlang this type is compatible with Erlang's iodata. On JavaScript this -/// type is compatible with normal strings. -/// -/// The BEAM virtual machine has an optimisation for appending strings, where it -/// will mutate the string buffer when safe to do so, so if you are looking to -/// build a string through appending many small strings then you may get better -/// performance by not using a string builder. Always benchmark your performance -/// sensitive code. -/// -pub type StringBuilder - -/// Create an empty `StringBuilder`. Useful as the start of a pipe chaining many -/// builders together. -/// -pub fn new() -> StringBuilder { - do_from_strings([]) -} - -/// Prepends a `String` onto the start of some `StringBuilder`. -/// -/// Runs in constant time. -/// -pub fn prepend( - to builder: StringBuilder, - prefix prefix: String, -) -> StringBuilder { - append_builder(from_string(prefix), builder) -} - -/// Appends a `String` onto the end of some `StringBuilder`. -/// -/// Runs in constant time. -/// -pub fn append(to builder: StringBuilder, suffix second: String) -> StringBuilder { - append_builder(builder, from_string(second)) -} - -/// Prepends some `StringBuilder` onto the start of another. -/// -/// Runs in constant time. -/// -pub fn prepend_builder( - to builder: StringBuilder, - prefix prefix: StringBuilder, -) -> StringBuilder { - do_append(prefix, builder) -} - -/// Appends some `StringBuilder` onto the end of another. -/// -/// Runs in constant time. -/// -pub fn append_builder( - to builder: StringBuilder, - suffix suffix: StringBuilder, -) -> StringBuilder { - do_append(builder, suffix) -} - -@external(erlang, "gleam_stdlib", "iodata_append") -@external(javascript, "../gleam_stdlib.mjs", "add") -fn do_append(a: StringBuilder, b: StringBuilder) -> StringBuilder - -/// Converts a list of strings into a builder. -/// -/// Runs in constant time. -/// -pub fn from_strings(strings: List(String)) -> StringBuilder { - do_from_strings(strings) -} - -@external(erlang, "gleam_stdlib", "identity") -@external(javascript, "../gleam_stdlib.mjs", "concat") -fn do_from_strings(a: List(String)) -> StringBuilder - -/// Joins a list of builders into a single builder. -/// -/// Runs in constant time. -/// -pub fn concat(builders: List(StringBuilder)) -> StringBuilder { - do_concat(builders) -} - -@external(erlang, "gleam_stdlib", "identity") -@external(javascript, "../gleam_stdlib.mjs", "concat") -fn do_concat(builders: List(StringBuilder)) -> StringBuilder - -/// Converts a string into a builder. -/// -/// Runs in constant time. -/// -pub fn from_string(string: String) -> StringBuilder { - do_from_string(string) -} - -@external(erlang, "gleam_stdlib", "identity") -@external(javascript, "../gleam_stdlib.mjs", "identity") -fn do_from_string(string: String) -> StringBuilder - -/// Turns an `StringBuilder` into a `String` -/// -/// This function is implemented natively by the virtual machine and is highly -/// optimised. -/// -pub fn to_string(builder: StringBuilder) -> String { - do_to_string(builder) -} - -@external(erlang, "unicode", "characters_to_binary") -@external(javascript, "../gleam_stdlib.mjs", "identity") -fn do_to_string(builder: StringBuilder) -> String - -/// Returns the size of the `StringBuilder` in bytes. -/// -pub fn byte_size(builder: StringBuilder) -> Int { - do_byte_size(builder) -} - -@external(erlang, "erlang", "iolist_size") -@external(javascript, "../gleam_stdlib.mjs", "length") -fn do_byte_size(builder: StringBuilder) -> Int - -/// Joins the given builders into a new builder separated with the given string -/// -pub fn join(builders: List(StringBuilder), with sep: String) -> StringBuilder { - builders - |> list.intersperse(from_string(sep)) - |> concat -} - -/// Converts a builder to a new builder where the contents have been -/// lowercased. -/// -pub fn lowercase(builder: StringBuilder) -> StringBuilder { - do_lowercase(builder) -} - -@external(erlang, "string", "lowercase") -@external(javascript, "../gleam_stdlib.mjs", "lowercase") -fn do_lowercase(builder: StringBuilder) -> StringBuilder - -/// Converts a builder to a new builder where the contents have been -/// uppercased. -/// -pub fn uppercase(builder: StringBuilder) -> StringBuilder { - do_uppercase(builder) -} - -@external(erlang, "string", "uppercase") -@external(javascript, "../gleam_stdlib.mjs", "uppercase") -fn do_uppercase(builder: StringBuilder) -> StringBuilder - -/// Converts a builder to a new builder with the contents reversed. -/// -pub fn reverse(builder: StringBuilder) -> StringBuilder { - do_reverse(builder) -} - -@external(erlang, "string", "reverse") -fn do_reverse(builder: StringBuilder) -> StringBuilder { - builder - |> to_string - |> do_to_graphemes - |> list.reverse - |> from_strings -} - -@external(javascript, "../gleam_stdlib.mjs", "graphemes") -fn do_to_graphemes(string: String) -> List(String) - -/// Splits a builder on a given pattern into a list of builders. -/// -pub fn split(iodata: StringBuilder, on pattern: String) -> List(StringBuilder) { - do_split(iodata, pattern) -} - -type Direction { - All -} - -@external(javascript, "../gleam_stdlib.mjs", "split") -fn do_split(iodata: StringBuilder, pattern: String) -> List(StringBuilder) { - erl_split(iodata, pattern, All) -} - -@external(erlang, "string", "split") -fn erl_split(a: StringBuilder, b: String, c: Direction) -> List(StringBuilder) - -/// Replaces all instances of a pattern with a given string substitute. -/// -@external(erlang, "gleam_stdlib", "string_replace") -@external(javascript, "../gleam_stdlib.mjs", "string_replace") -pub fn replace( - in builder: StringBuilder, - each pattern: String, - with substitute: String, -) -> StringBuilder - -/// Compares two builders to determine if they have the same textual content. -/// -/// Comparing two iodata using the `==` operator may return `False` even if they -/// have the same content as they may have been build in different ways, so -/// using this function is often preferred. -/// -/// ## Examples -/// -/// ```gleam -/// from_strings(["a", "b"]) == from_string("ab") -/// // -> False -/// ``` -/// -/// ```gleam -/// is_equal(from_strings(["a", "b"]), from_string("ab")) -/// // -> True -/// ``` -/// -@external(erlang, "string", "equal") -pub fn is_equal(a: StringBuilder, b: StringBuilder) -> Bool { - a == b -} - -/// Inspects a builder to determine if it is equivalent to an empty string. -/// -/// ## Examples -/// -/// ```gleam -/// from_string("ok") |> is_empty -/// // -> False -/// ``` -/// -/// ```gleam -/// from_string("") |> is_empty -/// // -> True -/// ``` -/// -/// ```gleam -/// from_strings([]) |> is_empty -/// // -> True -/// ``` -/// -@external(erlang, "string", "is_empty") -pub fn is_empty(builder: StringBuilder) -> Bool { - from_string("") == builder -} diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/uri.gleam b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/uri.gleam deleted file mode 100644 index b317f4b9559..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam/uri.gleam +++ /dev/null @@ -1,447 +0,0 @@ -//// Utilities for working with URIs -//// -//// This module provides functions for working with URIs (for example, parsing -//// URIs or encoding query strings). The functions in this module are implemented -//// according to [RFC 3986](https://tools.ietf.org/html/rfc3986). -//// -//// Query encoding (Form encoding) is defined in the -//// [W3C specification](https://www.w3.org/TR/html52/sec-forms.html#urlencoded-form-data). - -import gleam/int -import gleam/list -import gleam/option.{type Option, None, Some} -import gleam/pair -import gleam/regex -import gleam/result -import gleam/string -import gleam/string_builder.{type StringBuilder} - -/// Type representing holding the parsed components of an URI. -/// All components of a URI are optional, except the path. -/// -pub type Uri { - Uri( - scheme: Option(String), - userinfo: Option(String), - host: Option(String), - port: Option(Int), - path: String, - query: Option(String), - fragment: Option(String), - ) -} - -/// Parses a compliant URI string into the `Uri` Type. -/// If the string is not a valid URI string then an error is returned. -/// -/// The opposite operation is `uri.to_string`. -/// -/// ## Examples -/// -/// ```gleam -/// parse("https://example.com:1234/a/b?query=true#fragment") -/// // -> Ok( -/// // Uri( -/// // scheme: Some("https"), -/// // userinfo: None, -/// // host: Some("example.com"), -/// // port: Some(1234), -/// // path: "/a/b", -/// // query: Some("query=true"), -/// // fragment: Some("fragment") -/// // ) -/// // ) -/// ``` -/// -pub fn parse(uri_string: String) -> Result(Uri, Nil) { - do_parse(uri_string) -} - -@external(erlang, "gleam_stdlib", "uri_parse") -fn do_parse(uri_string: String) -> Result(Uri, Nil) { - // From https://tools.ietf.org/html/rfc3986#appendix-B - let pattern = - // 12 3 4 5 6 7 8 - "^(([a-z][a-z0-9\\+\\-\\.]*):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#.*)?" - let matches = - pattern - |> regex_submatches(uri_string) - |> pad_list(8) - - let #(scheme, authority, path, query, fragment) = case matches { - [ - _scheme_with_colon, - scheme, - authority_with_slashes, - _authority, - path, - query_with_question_mark, - _query, - fragment, - ] -> #( - scheme, - authority_with_slashes, - path, - query_with_question_mark, - fragment, - ) - _ -> #(None, None, None, None, None) - } - - let scheme = noneify_empty_string(scheme) - let path = option.unwrap(path, "") - let query = noneify_query(query) - let #(userinfo, host, port) = split_authority(authority) - let fragment = - fragment - |> option.to_result(Nil) - |> result.try(string.pop_grapheme) - |> result.map(pair.second) - |> option.from_result - let scheme = - scheme - |> noneify_empty_string - |> option.map(string.lowercase) - Ok(Uri( - scheme: scheme, - userinfo: userinfo, - host: host, - port: port, - path: path, - query: query, - fragment: fragment, - )) -} - -fn regex_submatches(pattern: String, string: String) -> List(Option(String)) { - pattern - |> regex.compile(regex.Options(case_insensitive: True, multi_line: False)) - |> result.nil_error - |> result.map(regex.scan(_, string)) - |> result.try(list.first) - |> result.map(fn(m: regex.Match) { m.submatches }) - |> result.unwrap([]) -} - -fn noneify_query(x: Option(String)) -> Option(String) { - case x { - None -> None - Some(x) -> - case string.pop_grapheme(x) { - Ok(#("?", query)) -> Some(query) - _ -> None - } - } -} - -fn noneify_empty_string(x: Option(String)) -> Option(String) { - case x { - Some("") | None -> None - Some(_) -> x - } -} - -// Split an authority into its userinfo, host and port parts. -fn split_authority( - authority: Option(String), -) -> #(Option(String), Option(String), Option(Int)) { - case option.unwrap(authority, "") { - "" -> #(None, None, None) - "//" -> #(None, Some(""), None) - authority -> { - let matches = - "^(//)?((.*)@)?(\\[[a-zA-Z0-9:.]*\\]|[^:]*)(:(\\d*))?" - |> regex_submatches(authority) - |> pad_list(6) - case matches { - [_, _, userinfo, host, _, port] -> { - let userinfo = noneify_empty_string(userinfo) - let host = noneify_empty_string(host) - let port = - port - |> option.unwrap("") - |> int.parse - |> option.from_result - #(userinfo, host, port) - } - _ -> #(None, None, None) - } - } - } -} - -fn pad_list(list: List(Option(a)), size: Int) -> List(Option(a)) { - list - |> list.append(list.repeat(None, extra_required(list, size))) -} - -fn extra_required(list: List(a), remaining: Int) -> Int { - case list { - _ if remaining == 0 -> 0 - [] -> remaining - [_, ..rest] -> extra_required(rest, remaining - 1) - } -} - -/// Parses an urlencoded query string into a list of key value pairs. -/// Returns an error for invalid encoding. -/// -/// The opposite operation is `uri.query_to_string`. -/// -/// ## Examples -/// -/// ```gleam -/// parse_query("a=1&b=2") -/// // -> Ok([#("a", "1"), #("b", "2")]) -/// ``` -/// -pub fn parse_query(query: String) -> Result(List(#(String, String)), Nil) { - do_parse_query(query) -} - -@external(erlang, "gleam_stdlib", "parse_query") -@external(javascript, "../gleam_stdlib.mjs", "parse_query") -fn do_parse_query(a: String) -> Result(List(#(String, String)), Nil) - -/// Encodes a list of key value pairs as a URI query string. -/// -/// The opposite operation is `uri.parse_query`. -/// -/// ## Examples -/// -/// ```gleam -/// query_to_string([#("a", "1"), #("b", "2")]) -/// // -> "a=1&b=2" -/// ``` -/// -pub fn query_to_string(query: List(#(String, String))) -> String { - query - |> list.map(query_pair) - |> list.intersperse(string_builder.from_string("&")) - |> string_builder.concat - |> string_builder.to_string -} - -fn query_pair(pair: #(String, String)) -> StringBuilder { - string_builder.from_strings([ - percent_encode(pair.0), - "=", - percent_encode(pair.1), - ]) -} - -/// Encodes a string into a percent encoded representation. -/// -/// ## Examples -/// -/// ```gleam -/// percent_encode("100% great") -/// // -> "100%25%20great" -/// ``` -/// -pub fn percent_encode(value: String) -> String { - do_percent_encode(value) -} - -@external(erlang, "gleam_stdlib", "percent_encode") -@external(javascript, "../gleam_stdlib.mjs", "percent_encode") -fn do_percent_encode(a: String) -> String - -/// Decodes a percent encoded string. -/// -/// ## Examples -/// -/// ```gleam -/// percent_decode("100%25%20great+fun") -/// // -> Ok("100% great+fun") -/// ``` -/// -pub fn percent_decode(value: String) -> Result(String, Nil) { - do_percent_decode(value) -} - -@external(erlang, "gleam_stdlib", "percent_decode") -@external(javascript, "../gleam_stdlib.mjs", "percent_decode") -fn do_percent_decode(a: String) -> Result(String, Nil) - -fn do_remove_dot_segments( - input: List(String), - accumulator: List(String), -) -> List(String) { - case input { - [] -> list.reverse(accumulator) - [segment, ..rest] -> { - let accumulator = case segment, accumulator { - "", accumulator -> accumulator - ".", accumulator -> accumulator - "..", [] -> [] - "..", [_, ..accumulator] -> accumulator - segment, accumulator -> [segment, ..accumulator] - } - do_remove_dot_segments(rest, accumulator) - } - } -} - -fn remove_dot_segments(input: List(String)) -> List(String) { - do_remove_dot_segments(input, []) -} - -/// Splits the path section of a URI into it's constituent segments. -/// -/// Removes empty segments and resolves dot-segments as specified in -/// [section 5.2](https://www.ietf.org/rfc/rfc3986.html#section-5.2) of the RFC. -/// -/// ## Examples -/// -/// ```gleam -/// path_segments("/users/1") -/// // -> ["users" ,"1"] -/// ``` -/// -pub fn path_segments(path: String) -> List(String) { - remove_dot_segments(string.split(path, "/")) -} - -/// Encodes a `Uri` value as a URI string. -/// -/// The opposite operation is `uri.parse`. -/// -/// ## Examples -/// -/// ```gleam -/// let uri = Uri(Some("http"), None, Some("example.com"), ...) -/// to_string(uri) -/// // -> "http://example.com" -/// ``` -/// -pub fn to_string(uri: Uri) -> String { - let parts = case uri.fragment { - Some(fragment) -> ["#", fragment] - _ -> [] - } - let parts = case uri.query { - Some(query) -> ["?", query, ..parts] - _ -> parts - } - let parts = [uri.path, ..parts] - let parts = case uri.host, string.starts_with(uri.path, "/") { - Some(host), False if host != "" -> ["/", ..parts] - _, _ -> parts - } - let parts = case uri.host, uri.port { - Some(_), Some(port) -> [":", int.to_string(port), ..parts] - _, _ -> parts - } - let parts = case uri.scheme, uri.userinfo, uri.host { - Some(s), Some(u), Some(h) -> [s, "://", u, "@", h, ..parts] - Some(s), None, Some(h) -> [s, "://", h, ..parts] - Some(s), Some(_), None | Some(s), None, None -> [s, ":", ..parts] - None, None, Some(h) -> ["//", h, ..parts] - _, _, _ -> parts - } - string.concat(parts) -} - -/// Fetches the origin of a URI. -/// -/// Returns the origin of a uri as defined in -/// [RFC 6454](https://tools.ietf.org/html/rfc6454) -/// -/// The supported URI schemes are `http` and `https`. -/// URLs without a scheme will return `Error`. -/// -/// ## Examples -/// -/// ```gleam -/// let assert Ok(uri) = parse("http://example.com/path?foo#bar") -/// origin(uri) -/// // -> Ok("http://example.com") -/// ``` -/// -pub fn origin(uri: Uri) -> Result(String, Nil) { - let Uri(scheme: scheme, host: host, port: port, ..) = uri - case host, scheme { - Some(h), Some("https") if port == Some(443) -> - Ok(string.concat(["https://", h])) - Some(h), Some("http") if port == Some(80) -> - Ok(string.concat(["http://", h])) - Some(h), Some(s) if s == "http" || s == "https" -> { - case port { - Some(p) -> Ok(string.concat([s, "://", h, ":", int.to_string(p)])) - None -> Ok(string.concat([s, "://", h])) - } - } - _, _ -> Error(Nil) - } -} - -fn drop_last(elements: List(a)) -> List(a) { - list.take(from: elements, up_to: list.length(elements) - 1) -} - -fn join_segments(segments: List(String)) -> String { - string.join(["", ..segments], "/") -} - -/// Resolves a URI with respect to the given base URI. -/// -/// The base URI must be an absolute URI or this function will return an error. -/// The algorithm for merging uris is described in -/// [RFC 3986](https://tools.ietf.org/html/rfc3986#section-5.2). -/// -pub fn merge(base: Uri, relative: Uri) -> Result(Uri, Nil) { - case base { - Uri(scheme: Some(_), host: Some(_), ..) -> - case relative { - Uri(host: Some(_), ..) -> { - let path = - string.split(relative.path, "/") - |> remove_dot_segments() - |> join_segments() - let resolved = - Uri( - option.or(relative.scheme, base.scheme), - None, - relative.host, - option.or(relative.port, base.port), - path, - relative.query, - relative.fragment, - ) - Ok(resolved) - } - _ -> { - let #(new_path, new_query) = case relative.path { - "" -> #(base.path, option.or(relative.query, base.query)) - _ -> { - let path_segments = case string.starts_with(relative.path, "/") { - True -> string.split(relative.path, "/") - False -> - string.split(base.path, "/") - |> drop_last() - |> list.append(string.split(relative.path, "/")) - } - let path = - path_segments - |> remove_dot_segments() - |> join_segments() - #(path, relative.query) - } - } - let resolved = - Uri( - base.scheme, - None, - base.host, - base.port, - new_path, - new_query, - relative.fragment, - ) - Ok(resolved) - } - } - _ -> Error(Nil) - } -} diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@bit_array.erl b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@bit_array.erl deleted file mode 100644 index d5cba7bcebd..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@bit_array.erl +++ /dev/null @@ -1,213 +0,0 @@ --module(gleam@bit_array). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([from_string/1, byte_size/1, slice/3, is_utf8/1, to_string/1, concat/1, append/2, base64_encode/2, base64_decode/1, base64_url_encode/2, base64_url_decode/1, base16_encode/1, base16_decode/1, inspect/1, compare/2]). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bit_array.gleam", 11). --spec from_string(binary()) -> bitstring(). -from_string(X) -> - gleam_stdlib:identity(X). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bit_array.gleam", 17). --spec byte_size(bitstring()) -> integer(). -byte_size(X) -> - erlang:byte_size(X). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bit_array.gleam", 42). --spec slice(bitstring(), integer(), integer()) -> {ok, bitstring()} | - {error, nil}. -slice(String, Position, Length) -> - gleam_stdlib:bit_array_slice(String, Position, Length). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bit_array.gleam", 55). --spec do_is_utf8(bitstring()) -> boolean(). -do_is_utf8(Bits) -> - case Bits of - <<>> -> - true; - - <<_/utf8, Rest/binary>> -> - do_is_utf8(Rest); - - _ -> - false - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/bit_array.gleam", 50). --spec is_utf8(bitstring()) -> boolean(). -is_utf8(Bits) -> - do_is_utf8(Bits). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bit_array.gleam", 83). --spec do_to_string(bitstring()) -> {ok, binary()} | {error, nil}. -do_to_string(Bits) -> - case is_utf8(Bits) of - true -> - {ok, gleam_stdlib:identity(Bits)}; - - false -> - {error, nil} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/bit_array.gleam", 75). --spec to_string(bitstring()) -> {ok, binary()} | {error, nil}. -to_string(Bits) -> - do_to_string(Bits). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bit_array.gleam", 101). --spec concat(list(bitstring())) -> bitstring(). -concat(Bit_arrays) -> - gleam_stdlib:bit_array_concat(Bit_arrays). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bit_array.gleam", 28). --spec append(bitstring(), bitstring()) -> bitstring(). -append(First, Second) -> - gleam_stdlib:bit_array_concat([First, Second]). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bit_array.gleam", 107). --spec base64_encode(bitstring(), boolean()) -> binary(). -base64_encode(Input, Padding) -> - gleam_stdlib:bit_array_base64_encode(Input, Padding). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bit_array.gleam", 111). --spec base64_decode(binary()) -> {ok, bitstring()} | {error, nil}. -base64_decode(Encoded) -> - Padded = case erlang:byte_size(gleam_stdlib:identity(Encoded)) rem 4 of - 0 -> - Encoded; - - N -> - gleam@string:append( - Encoded, - gleam@string:repeat(<<"="/utf8>>, 4 - N) - ) - end, - gleam_stdlib:base_decode64(Padded). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bit_array.gleam", 125). --spec base64_url_encode(bitstring(), boolean()) -> binary(). -base64_url_encode(Input, Padding) -> - _pipe = gleam_stdlib:bit_array_base64_encode(Input, Padding), - _pipe@1 = gleam@string:replace(_pipe, <<"+"/utf8>>, <<"-"/utf8>>), - gleam@string:replace(_pipe@1, <<"/"/utf8>>, <<"_"/utf8>>). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bit_array.gleam", 133). --spec base64_url_decode(binary()) -> {ok, bitstring()} | {error, nil}. -base64_url_decode(Encoded) -> - _pipe = Encoded, - _pipe@1 = gleam@string:replace(_pipe, <<"-"/utf8>>, <<"+"/utf8>>), - _pipe@2 = gleam@string:replace(_pipe@1, <<"_"/utf8>>, <<"/"/utf8>>), - base64_decode(_pipe@2). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bit_array.gleam", 142). --spec base16_encode(bitstring()) -> binary(). -base16_encode(Input) -> - binary:encode_hex(Input). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bit_array.gleam", 146). --spec base16_decode(binary()) -> {ok, bitstring()} | {error, nil}. -base16_decode(Input) -> - gleam_stdlib:base16_decode(Input). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bit_array.gleam", 165). --spec do_inspect(bitstring(), binary()) -> binary(). -do_inspect(Input, Accumulator) -> - case Input of - <<>> -> - Accumulator; - - <> -> - <<<>/binary, - ":size(1)"/utf8>>; - - <> -> - <<<>/binary, - ":size(2)"/utf8>>; - - <> -> - <<<>/binary, - ":size(3)"/utf8>>; - - <> -> - <<<>/binary, - ":size(4)"/utf8>>; - - <> -> - <<<>/binary, - ":size(5)"/utf8>>; - - <> -> - <<<>/binary, - ":size(6)"/utf8>>; - - <> -> - <<<>/binary, - ":size(7)"/utf8>>; - - <> -> - Suffix = case Rest of - <<>> -> - <<""/utf8>>; - - _ -> - <<", "/utf8>> - end, - Accumulator@1 = <<<>/binary, - Suffix/binary>>, - do_inspect(Rest, Accumulator@1); - - _ -> - Accumulator - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/bit_array.gleam", 160). --spec inspect(bitstring()) -> binary(). -inspect(Input) -> - <<(do_inspect(Input, <<"<<"/utf8>>))/binary, ">>"/utf8>>. - --file("/Users/louis/src/gleam/stdlib/src/gleam/bit_array.gleam", 210). --spec compare(bitstring(), bitstring()) -> gleam@order:order(). -compare(A, B) -> - case {A, B} of - {<>, - <>} -> - case {First_byte, Second_byte} of - {F, S} when F > S -> - gt; - - {F@1, S@1} when F@1 < S@1 -> - lt; - - {_, _} -> - compare(First_rest, Second_rest) - end; - - {<<>>, <<>>} -> - eq; - - {_, <<>>} -> - gt; - - {<<>>, _} -> - lt; - - {First, Second} -> - case {gleam_stdlib:bit_array_to_int_and_size(First), - gleam_stdlib:bit_array_to_int_and_size(Second)} of - {{A@1, _}, {B@1, _}} when A@1 > B@1 -> - gt; - - {{A@2, _}, {B@2, _}} when A@2 < B@2 -> - lt; - - {{_, Size_a}, {_, Size_b}} when Size_a > Size_b -> - gt; - - {{_, Size_a@1}, {_, Size_b@1}} when Size_a@1 < Size_b@1 -> - lt; - - {_, _} -> - eq - end - end. diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@bool.erl b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@bool.erl deleted file mode 100644 index 16b0a9df238..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@bool.erl +++ /dev/null @@ -1,100 +0,0 @@ --module(gleam@bool). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export(['and'/2, 'or'/2, negate/1, nor/2, nand/2, exclusive_or/2, exclusive_nor/2, compare/2, to_int/1, to_string/1, guard/3, lazy_guard/3]). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bool.gleam", 33). --spec 'and'(boolean(), boolean()) -> boolean(). -'and'(A, B) -> - A andalso B. - --file("/Users/louis/src/gleam/stdlib/src/gleam/bool.gleam", 59). --spec 'or'(boolean(), boolean()) -> boolean(). -'or'(A, B) -> - A orelse B. - --file("/Users/louis/src/gleam/stdlib/src/gleam/bool.gleam", 79). --spec negate(boolean()) -> boolean(). -negate(Bool) -> - not Bool. - --file("/Users/louis/src/gleam/stdlib/src/gleam/bool.gleam", 107). --spec nor(boolean(), boolean()) -> boolean(). -nor(A, B) -> - not (A orelse B). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bool.gleam", 135). --spec nand(boolean(), boolean()) -> boolean(). -nand(A, B) -> - not (A andalso B). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bool.gleam", 163). --spec exclusive_or(boolean(), boolean()) -> boolean(). -exclusive_or(A, B) -> - A /= B. - --file("/Users/louis/src/gleam/stdlib/src/gleam/bool.gleam", 191). --spec exclusive_nor(boolean(), boolean()) -> boolean(). -exclusive_nor(A, B) -> - A =:= B. - --file("/Users/louis/src/gleam/stdlib/src/gleam/bool.gleam", 206). --spec compare(boolean(), boolean()) -> gleam@order:order(). -compare(A, B) -> - case {A, B} of - {true, true} -> - eq; - - {true, false} -> - gt; - - {false, false} -> - eq; - - {false, true} -> - lt - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/bool.gleam", 229). --spec to_int(boolean()) -> integer(). -to_int(Bool) -> - case Bool of - false -> - 0; - - true -> - 1 - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/bool.gleam", 250). --spec to_string(boolean()) -> binary(). -to_string(Bool) -> - case Bool of - false -> - <<"False"/utf8>>; - - true -> - <<"True"/utf8>> - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/bool.gleam", 309). --spec guard(boolean(), BVG, fun(() -> BVG)) -> BVG. -guard(Requirement, Consequence, Alternative) -> - case Requirement of - true -> - Consequence; - - false -> - Alternative() - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/bool.gleam", 350). --spec lazy_guard(boolean(), fun(() -> BVH), fun(() -> BVH)) -> BVH. -lazy_guard(Requirement, Consequence, Alternative) -> - case Requirement of - true -> - Consequence(); - - false -> - Alternative() - end. diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@bytes_builder.erl b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@bytes_builder.erl deleted file mode 100644 index a487e08aca5..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@bytes_builder.erl +++ /dev/null @@ -1,102 +0,0 @@ --module(gleam@bytes_builder). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([append_builder/2, prepend_builder/2, concat/1, new/0, from_string/1, prepend_string/2, append_string/2, from_string_builder/1, from_bit_array/1, prepend/2, append/2, concat_bit_arrays/1, to_bit_array/1, byte_size/1]). --export_type([bytes_builder/0]). - --opaque bytes_builder() :: {bytes, bitstring()} | - {text, gleam@string_builder:string_builder()} | - {many, list(bytes_builder())}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/bytes_builder.gleam", 72). --spec append_builder(bytes_builder(), bytes_builder()) -> bytes_builder(). -append_builder(First, Second) -> - gleam_stdlib:iodata_append(First, Second). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bytes_builder.gleam", 60). --spec prepend_builder(bytes_builder(), bytes_builder()) -> bytes_builder(). -prepend_builder(Second, First) -> - gleam_stdlib:iodata_append(First, Second). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bytes_builder.gleam", 111). --spec concat(list(bytes_builder())) -> bytes_builder(). -concat(Builders) -> - gleam_stdlib:identity(Builders). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bytes_builder.gleam", 36). --spec new() -> bytes_builder(). -new() -> - gleam_stdlib:identity([]). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bytes_builder.gleam", 132). --spec from_string(binary()) -> bytes_builder(). -from_string(String) -> - gleam_stdlib:wrap_list(String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bytes_builder.gleam", 87). --spec prepend_string(bytes_builder(), binary()) -> bytes_builder(). -prepend_string(Second, First) -> - gleam_stdlib:iodata_append(gleam_stdlib:wrap_list(First), Second). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bytes_builder.gleam", 99). --spec append_string(bytes_builder(), binary()) -> bytes_builder(). -append_string(First, Second) -> - gleam_stdlib:iodata_append(First, gleam_stdlib:wrap_list(Second)). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bytes_builder.gleam", 142). --spec from_string_builder(gleam@string_builder:string_builder()) -> bytes_builder(). -from_string_builder(Builder) -> - gleam_stdlib:wrap_list(Builder). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bytes_builder.gleam", 151). --spec from_bit_array(bitstring()) -> bytes_builder(). -from_bit_array(Bits) -> - gleam_stdlib:wrap_list(Bits). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bytes_builder.gleam", 44). --spec prepend(bytes_builder(), bitstring()) -> bytes_builder(). -prepend(Second, First) -> - gleam_stdlib:iodata_append(gleam_stdlib:wrap_list(First), Second). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bytes_builder.gleam", 52). --spec append(bytes_builder(), bitstring()) -> bytes_builder(). -append(First, Second) -> - gleam_stdlib:iodata_append(First, gleam_stdlib:wrap_list(Second)). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bytes_builder.gleam", 120). --spec concat_bit_arrays(list(bitstring())) -> bytes_builder(). -concat_bit_arrays(Bits) -> - gleam_stdlib:identity(Bits). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bytes_builder.gleam", 170). --spec to_list(list(list(bytes_builder())), list(bitstring())) -> list(bitstring()). -to_list(Stack, Acc) -> - case Stack of - [] -> - Acc; - - [[] | Remaining_stack] -> - to_list(Remaining_stack, Acc); - - [[{bytes, Bits} | Rest] | Remaining_stack@1] -> - to_list([Rest | Remaining_stack@1], [Bits | Acc]); - - [[{text, Builder} | Rest@1] | Remaining_stack@2] -> - Bits@1 = gleam_stdlib:identity( - gleam@string_builder:to_string(Builder) - ), - to_list([Rest@1 | Remaining_stack@2], [Bits@1 | Acc]); - - [[{many, Builders} | Rest@2] | Remaining_stack@3] -> - to_list([Builders, Rest@2 | Remaining_stack@3], Acc) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/bytes_builder.gleam", 163). --spec to_bit_array(bytes_builder()) -> bitstring(). -to_bit_array(Builder) -> - erlang:list_to_bitstring(Builder). - --file("/Users/louis/src/gleam/stdlib/src/gleam/bytes_builder.gleam", 197). --spec byte_size(bytes_builder()) -> integer(). -byte_size(Builder) -> - erlang:iolist_size(Builder). diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@dict.erl b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@dict.erl deleted file mode 100644 index 658b859d62b..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@dict.erl +++ /dev/null @@ -1,224 +0,0 @@ --module(gleam@dict). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([size/1, to_list/1, new/0, is_empty/1, get/2, has_key/2, insert/3, from_list/1, keys/1, values/1, take/2, merge/2, delete/2, drop/2, upsert/3, fold/3, map_values/2, filter/2, each/2, combine/3]). --export_type([dict/2]). - --type dict(KM, KN) :: any() | {gleam_phantom, KM, KN}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 36). --spec size(dict(any(), any())) -> integer(). -size(Dict) -> - maps:size(Dict). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 80). --spec to_list(dict(KW, KX)) -> list({KW, KX}). -to_list(Dict) -> - maps:to_list(Dict). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 127). --spec new() -> dict(any(), any()). -new() -> - maps:new(). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 52). --spec is_empty(dict(any(), any())) -> boolean(). -is_empty(Dict) -> - Dict =:= new(). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 152). --spec get(dict(MD, ME), MD) -> {ok, ME} | {error, nil}. -get(From, Get) -> - gleam_stdlib:map_get(From, Get). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 116). --spec has_key(dict(LN, any()), LN) -> boolean(). -has_key(Dict, Key) -> - maps:is_key(Key, Dict). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 177). --spec insert(dict(MP, MQ), MP, MQ) -> dict(MP, MQ). -insert(Dict, Key, Value) -> - maps:put(Key, Value, Dict). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 92). --spec fold_list_of_pair(list({LG, LH}), dict(LG, LH)) -> dict(LG, LH). -fold_list_of_pair(List, Initial) -> - case List of - [] -> - Initial; - - [X | Rest] -> - fold_list_of_pair( - Rest, - insert(Initial, erlang:element(1, X), erlang:element(2, X)) - ) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 88). --spec from_list(list({LB, LC})) -> dict(LB, LC). -from_list(List) -> - maps:from_list(List). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 229). --spec reverse_and_concat(list(NZ), list(NZ)) -> list(NZ). -reverse_and_concat(Remaining, Accumulator) -> - case Remaining of - [] -> - Accumulator; - - [Item | Rest] -> - reverse_and_concat(Rest, [Item | Accumulator]) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 236). --spec do_keys_acc(list({OD, any()}), list(OD)) -> list(OD). -do_keys_acc(List, Acc) -> - case List of - [] -> - reverse_and_concat(Acc, []); - - [First | Rest] -> - do_keys_acc(Rest, [erlang:element(1, First) | Acc]) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 219). --spec keys(dict(NP, any())) -> list(NP). -keys(Dict) -> - maps:keys(Dict). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 266). --spec do_values_acc(list({any(), OT}), list(OT)) -> list(OT). -do_values_acc(List, Acc) -> - case List of - [] -> - reverse_and_concat(Acc, []); - - [First | Rest] -> - do_values_acc(Rest, [erlang:element(2, First) | Acc]) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 256). --spec values(dict(any(), OJ)) -> list(OJ). -values(Dict) -> - maps:values(Dict). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 335). --spec insert_taken(dict(PX, PY), list(PX), dict(PX, PY)) -> dict(PX, PY). -insert_taken(Dict, Desired_keys, Acc) -> - Insert = fun(Taken, Key) -> case get(Dict, Key) of - {ok, Value} -> - insert(Taken, Key, Value); - - _ -> - Taken - end end, - case Desired_keys of - [] -> - Acc; - - [First | Rest] -> - insert_taken(Dict, Rest, Insert(Acc, First)) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 326). --spec take(dict(PJ, PK), list(PJ)) -> dict(PJ, PK). -take(Dict, Desired_keys) -> - maps:with(Desired_keys, Dict). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 377). --spec insert_pair(dict(QW, QX), {QW, QX}) -> dict(QW, QX). -insert_pair(Dict, Pair) -> - insert(Dict, erlang:element(1, Pair), erlang:element(2, Pair)). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 381). --spec fold_inserts(list({RC, RD}), dict(RC, RD)) -> dict(RC, RD). -fold_inserts(New_entries, Dict) -> - case New_entries of - [] -> - Dict; - - [First | Rest] -> - fold_inserts(Rest, insert_pair(Dict, First)) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 366). --spec merge(dict(QG, QH), dict(QG, QH)) -> dict(QG, QH). -merge(Dict, New_entries) -> - maps:merge(Dict, New_entries). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 403). --spec delete(dict(RJ, RK), RJ) -> dict(RJ, RK). -delete(Dict, Key) -> - maps:remove(Key, Dict). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 431). --spec drop(dict(RV, RW), list(RV)) -> dict(RV, RW). -drop(Dict, Disallowed_keys) -> - case Disallowed_keys of - [] -> - Dict; - - [First | Rest] -> - drop(delete(Dict, First), Rest) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 461). --spec upsert(dict(SC, SD), SC, fun((gleam@option:option(SD)) -> SD)) -> dict(SC, SD). -upsert(Dict, Key, Fun) -> - _pipe = Dict, - _pipe@1 = get(_pipe, Key), - _pipe@2 = gleam@option:from_result(_pipe@1), - _pipe@3 = Fun(_pipe@2), - insert(Dict, Key, _pipe@3). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 473). --spec do_fold(list({SJ, SK}), SM, fun((SM, SJ, SK) -> SM)) -> SM. -do_fold(List, Initial, Fun) -> - case List of - [] -> - Initial; - - [{K, V} | Rest] -> - do_fold(Rest, Fun(Initial, K, V), Fun) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 505). --spec fold(dict(SN, SO), SR, fun((SR, SN, SO) -> SR)) -> SR. -fold(Dict, Initial, Fun) -> - _pipe = Dict, - _pipe@1 = maps:to_list(_pipe), - do_fold(_pipe@1, Initial, Fun). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 196). --spec map_values(dict(NB, NC), fun((NB, NC) -> NF)) -> dict(NB, NF). -map_values(Dict, Fun) -> - maps:map(Fun, Dict). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 290). --spec filter(dict(OX, OY), fun((OX, OY) -> boolean())) -> dict(OX, OY). -filter(Dict, Predicate) -> - maps:filter(Predicate, Dict). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 537). --spec each(dict(SS, ST), fun((SS, ST) -> any())) -> nil. -each(Dict, Fun) -> - fold( - Dict, - nil, - fun(Nil, K, V) -> - Fun(K, V), - Nil - end - ). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dict.gleam", 558). --spec combine(dict(SX, SY), dict(SX, SY), fun((SY, SY) -> SY)) -> dict(SX, SY). -combine(Dict, Other, Fun) -> - fold(Dict, Other, fun(Acc, Key, Value) -> case get(Acc, Key) of - {ok, Other_value} -> - insert(Acc, Key, Fun(Value, Other_value)); - - {error, _} -> - insert(Acc, Key, Value) - end end). diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@dynamic.erl b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@dynamic.erl deleted file mode 100644 index 5d4868e258a..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@dynamic.erl +++ /dev/null @@ -1,832 +0,0 @@ --module(gleam@dynamic). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([from/1, dynamic/1, bit_array/1, classify/1, int/1, float/1, bool/1, shallow_list/1, optional/1, any/1, decode1/2, result/2, list/1, string/1, field/2, optional_field/2, element/2, tuple2/2, tuple3/3, tuple4/4, tuple5/5, tuple6/6, dict/2, decode2/3, decode3/4, decode4/5, decode5/6, decode6/7, decode7/8, decode8/9, decode9/10]). --export_type([dynamic_/0, decode_error/0, unknown_tuple/0]). - --type dynamic_() :: any(). - --type decode_error() :: {decode_error, binary(), binary(), list(binary())}. - --type unknown_tuple() :: any(). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 31). --spec from(any()) -> dynamic_(). -from(A) -> - gleam_stdlib:identity(A). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 39). --spec dynamic(dynamic_()) -> {ok, dynamic_()} | {error, list(decode_error())}. -dynamic(Value) -> - {ok, Value}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 60). --spec bit_array(dynamic_()) -> {ok, bitstring()} | {error, list(decode_error())}. -bit_array(Data) -> - gleam_stdlib:decode_bit_array(Data). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 107). --spec put_expected(decode_error(), binary()) -> decode_error(). -put_expected(Error, Expected) -> - erlang:setelement(2, Error, Expected). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 118). --spec classify(dynamic_()) -> binary(). -classify(Data) -> - gleam_stdlib:classify_dynamic(Data). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 141). --spec int(dynamic_()) -> {ok, integer()} | {error, list(decode_error())}. -int(Data) -> - gleam_stdlib:decode_int(Data). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 164). --spec float(dynamic_()) -> {ok, float()} | {error, list(decode_error())}. -float(Data) -> - gleam_stdlib:decode_float(Data). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 187). --spec bool(dynamic_()) -> {ok, boolean()} | {error, list(decode_error())}. -bool(Data) -> - gleam_stdlib:decode_bool(Data). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 213). --spec shallow_list(dynamic_()) -> {ok, list(dynamic_())} | - {error, list(decode_error())}. -shallow_list(Value) -> - gleam_stdlib:decode_list(Value). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 356). --spec optional(fun((dynamic_()) -> {ok, CJC} | {error, list(decode_error())})) -> fun((dynamic_()) -> {ok, - gleam@option:option(CJC)} | - {error, list(decode_error())}). -optional(Decode) -> - fun(Value) -> gleam_stdlib:decode_option(Value, Decode) end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 491). --spec at_least_decode_tuple_error(integer(), dynamic_()) -> {ok, any()} | - {error, list(decode_error())}. -at_least_decode_tuple_error(Size, Data) -> - S = case Size of - 1 -> - <<""/utf8>>; - - _ -> - <<"s"/utf8>> - end, - Error = begin - _pipe = [<<"Tuple of at least "/utf8>>, - gleam@int:to_string(Size), - <<" element"/utf8>>, - S], - _pipe@1 = gleam@string_builder:from_strings(_pipe), - _pipe@2 = gleam@string_builder:to_string(_pipe@1), - {decode_error, _pipe@2, classify(Data), []} - end, - {error, [Error]}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 1021). --spec any(list(fun((dynamic_()) -> {ok, CNC} | {error, list(decode_error())}))) -> fun((dynamic_()) -> {ok, - CNC} | - {error, list(decode_error())}). -any(Decoders) -> - fun(Data) -> case Decoders of - [] -> - {error, - [{decode_error, <<"another type"/utf8>>, classify(Data), []}]}; - - [Decoder | Decoders@1] -> - case Decoder(Data) of - {ok, Decoded} -> - {ok, Decoded}; - - {error, _} -> - (any(Decoders@1))(Data) - end - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 1517). --spec all_errors({ok, any()} | {error, list(decode_error())}) -> list(decode_error()). -all_errors(Result) -> - case Result of - {ok, _} -> - []; - - {error, Errors} -> - Errors - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 1054). --spec decode1( - fun((CNG) -> CNH), - fun((dynamic_()) -> {ok, CNG} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, CNH} | {error, list(decode_error())}). -decode1(Constructor, T1) -> - fun(Value) -> case T1(Value) of - {ok, A} -> - {ok, Constructor(A)}; - - A@1 -> - {error, all_errors(A@1)} - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 563). --spec push_path(decode_error(), any()) -> decode_error(). -push_path(Error, Name) -> - Name@1 = gleam_stdlib:identity(Name), - Decoder = any( - [fun string/1, - fun(X) -> gleam@result:map(int(X), fun gleam@int:to_string/1) end] - ), - Name@3 = case Decoder(Name@1) of - {ok, Name@2} -> - Name@2; - - {error, _} -> - _pipe = [<<"<"/utf8>>, classify(Name@1), <<">"/utf8>>], - _pipe@1 = gleam@string_builder:from_strings(_pipe), - gleam@string_builder:to_string(_pipe@1) - end, - erlang:setelement(4, Error, [Name@3 | erlang:element(4, Error)]). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 248). --spec result( - fun((dynamic_()) -> {ok, CIQ} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CIS} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, {ok, CIQ} | {error, CIS}} | - {error, list(decode_error())}). -result(Decode_ok, Decode_error) -> - fun(Value) -> - gleam@result:'try'( - gleam_stdlib:decode_result(Value), - fun(Inner_result) -> case Inner_result of - {ok, Raw} -> - gleam@result:'try'( - begin - _pipe = Decode_ok(Raw), - map_errors( - _pipe, - fun(_capture) -> - push_path(_capture, <<"ok"/utf8>>) - end - ) - end, - fun(Value@1) -> {ok, {ok, Value@1}} end - ); - - {error, Raw@1} -> - gleam@result:'try'( - begin - _pipe@1 = Decode_error(Raw@1), - map_errors( - _pipe@1, - fun(_capture@1) -> - push_path(_capture@1, <<"error"/utf8>>) - end - ) - end, - fun(Value@2) -> {ok, {error, Value@2}} end - ) - end end - ) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 301). --spec list(fun((dynamic_()) -> {ok, CIX} | {error, list(decode_error())})) -> fun((dynamic_()) -> {ok, - list(CIX)} | - {error, list(decode_error())}). -list(Decoder_type) -> - fun(Dynamic) -> - gleam@result:'try'(shallow_list(Dynamic), fun(List) -> _pipe = List, - _pipe@1 = gleam@list:try_map(_pipe, Decoder_type), - map_errors( - _pipe@1, - fun(_capture) -> push_path(_capture, <<"*"/utf8>>) end - ) end) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 87). --spec map_errors( - {ok, CHL} | {error, list(decode_error())}, - fun((decode_error()) -> decode_error()) -) -> {ok, CHL} | {error, list(decode_error())}. -map_errors(Result, F) -> - gleam@result:map_error( - Result, - fun(_capture) -> gleam@list:map(_capture, F) end - ). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 95). --spec decode_string(dynamic_()) -> {ok, binary()} | - {error, list(decode_error())}. -decode_string(Data) -> - _pipe = bit_array(Data), - _pipe@1 = map_errors( - _pipe, - fun(_capture) -> put_expected(_capture, <<"String"/utf8>>) end - ), - gleam@result:'try'( - _pipe@1, - fun(Raw) -> case gleam@bit_array:to_string(Raw) of - {ok, String} -> - {ok, String}; - - {error, nil} -> - {error, - [{decode_error, - <<"String"/utf8>>, - <<"BitArray"/utf8>>, - []}]} - end end - ). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 83). --spec string(dynamic_()) -> {ok, binary()} | {error, list(decode_error())}. -string(Data) -> - decode_string(Data). - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 385). --spec field( - any(), - fun((dynamic_()) -> {ok, CJM} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, CJM} | {error, list(decode_error())}). -field(Name, Inner_type) -> - fun(Value) -> - Missing_field_error = {decode_error, - <<"field"/utf8>>, - <<"nothing"/utf8>>, - []}, - gleam@result:'try'( - gleam_stdlib:decode_field(Value, Name), - fun(Maybe_inner) -> _pipe = Maybe_inner, - _pipe@1 = gleam@option:to_result(_pipe, [Missing_field_error]), - _pipe@2 = gleam@result:'try'(_pipe@1, Inner_type), - map_errors( - _pipe@2, - fun(_capture) -> push_path(_capture, Name) end - ) end - ) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 427). --spec optional_field( - any(), - fun((dynamic_()) -> {ok, CJQ} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, gleam@option:option(CJQ)} | - {error, list(decode_error())}). -optional_field(Name, Inner_type) -> - fun(Value) -> - gleam@result:'try'( - gleam_stdlib:decode_field(Value, Name), - fun(Maybe_inner) -> case Maybe_inner of - none -> - {ok, none}; - - {some, Dynamic_inner} -> - _pipe = Inner_type(Dynamic_inner), - _pipe@1 = gleam@result:map( - _pipe, - fun(Field@0) -> {some, Field@0} end - ), - map_errors( - _pipe@1, - fun(_capture) -> push_path(_capture, Name) end - ) - end end - ) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 470). --spec element( - integer(), - fun((dynamic_()) -> {ok, CJY} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, CJY} | {error, list(decode_error())}). -element(Index, Inner_type) -> - fun(Data) -> - gleam@result:'try'( - gleam_stdlib:decode_tuple(Data), - fun(Tuple) -> - Size = gleam_stdlib:size_of_tuple(Tuple), - gleam@result:'try'(case Index >= 0 of - true -> - case Index < Size of - true -> - gleam_stdlib:tuple_get(Tuple, Index); - - false -> - at_least_decode_tuple_error(Index + 1, Data) - end; - - false -> - case gleam@int:absolute_value(Index) =< Size of - true -> - gleam_stdlib:tuple_get(Tuple, Size + Index); - - false -> - at_least_decode_tuple_error( - gleam@int:absolute_value(Index), - Data - ) - end - end, fun(Data@1) -> _pipe = Inner_type(Data@1), - map_errors( - _pipe, - fun(_capture) -> push_path(_capture, Index) end - ) end) - end - ) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 553). --spec tuple_errors({ok, any()} | {error, list(decode_error())}, binary()) -> list(decode_error()). -tuple_errors(Result, Name) -> - case Result of - {ok, _} -> - []; - - {error, Errors} -> - gleam@list:map( - Errors, - fun(_capture) -> push_path(_capture, Name) end - ) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 629). --spec tuple2( - fun((dynamic_()) -> {ok, CKY} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CLA} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, {CKY, CLA}} | {error, list(decode_error())}). -tuple2(Decode1, Decode2) -> - fun(Value) -> - gleam@result:'try'( - gleam_stdlib:decode_tuple2(Value), - fun(_use0) -> - {A, B} = _use0, - case {Decode1(A), Decode2(B)} of - {{ok, A@1}, {ok, B@1}} -> - {ok, {A@1, B@1}}; - - {A@2, B@2} -> - _pipe = tuple_errors(A@2, <<"0"/utf8>>), - _pipe@1 = lists:append( - _pipe, - tuple_errors(B@2, <<"1"/utf8>>) - ), - {error, _pipe@1} - end - end - ) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 698). --spec tuple3( - fun((dynamic_()) -> {ok, CLD} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CLF} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CLH} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, {CLD, CLF, CLH}} | {error, list(decode_error())}). -tuple3(Decode1, Decode2, Decode3) -> - fun(Value) -> - gleam@result:'try'( - gleam_stdlib:decode_tuple3(Value), - fun(_use0) -> - {A, B, C} = _use0, - case {Decode1(A), Decode2(B), Decode3(C)} of - {{ok, A@1}, {ok, B@1}, {ok, C@1}} -> - {ok, {A@1, B@1, C@1}}; - - {A@2, B@2, C@2} -> - _pipe = tuple_errors(A@2, <<"0"/utf8>>), - _pipe@1 = lists:append( - _pipe, - tuple_errors(B@2, <<"1"/utf8>>) - ), - _pipe@2 = lists:append( - _pipe@1, - tuple_errors(C@2, <<"2"/utf8>>) - ), - {error, _pipe@2} - end - end - ) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 769). --spec tuple4( - fun((dynamic_()) -> {ok, CLK} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CLM} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CLO} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CLQ} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, {CLK, CLM, CLO, CLQ}} | - {error, list(decode_error())}). -tuple4(Decode1, Decode2, Decode3, Decode4) -> - fun(Value) -> - gleam@result:'try'( - gleam_stdlib:decode_tuple4(Value), - fun(_use0) -> - {A, B, C, D} = _use0, - case {Decode1(A), Decode2(B), Decode3(C), Decode4(D)} of - {{ok, A@1}, {ok, B@1}, {ok, C@1}, {ok, D@1}} -> - {ok, {A@1, B@1, C@1, D@1}}; - - {A@2, B@2, C@2, D@2} -> - _pipe = tuple_errors(A@2, <<"0"/utf8>>), - _pipe@1 = lists:append( - _pipe, - tuple_errors(B@2, <<"1"/utf8>>) - ), - _pipe@2 = lists:append( - _pipe@1, - tuple_errors(C@2, <<"2"/utf8>>) - ), - _pipe@3 = lists:append( - _pipe@2, - tuple_errors(D@2, <<"3"/utf8>>) - ), - {error, _pipe@3} - end - end - ) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 842). --spec tuple5( - fun((dynamic_()) -> {ok, CLT} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CLV} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CLX} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CLZ} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CMB} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, {CLT, CLV, CLX, CLZ, CMB}} | - {error, list(decode_error())}). -tuple5(Decode1, Decode2, Decode3, Decode4, Decode5) -> - fun(Value) -> - gleam@result:'try'( - gleam_stdlib:decode_tuple5(Value), - fun(_use0) -> - {A, B, C, D, E} = _use0, - case {Decode1(A), - Decode2(B), - Decode3(C), - Decode4(D), - Decode5(E)} of - {{ok, A@1}, {ok, B@1}, {ok, C@1}, {ok, D@1}, {ok, E@1}} -> - {ok, {A@1, B@1, C@1, D@1, E@1}}; - - {A@2, B@2, C@2, D@2, E@2} -> - _pipe = tuple_errors(A@2, <<"0"/utf8>>), - _pipe@1 = lists:append( - _pipe, - tuple_errors(B@2, <<"1"/utf8>>) - ), - _pipe@2 = lists:append( - _pipe@1, - tuple_errors(C@2, <<"2"/utf8>>) - ), - _pipe@3 = lists:append( - _pipe@2, - tuple_errors(D@2, <<"3"/utf8>>) - ), - _pipe@4 = lists:append( - _pipe@3, - tuple_errors(E@2, <<"4"/utf8>>) - ), - {error, _pipe@4} - end - end - ) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 917). --spec tuple6( - fun((dynamic_()) -> {ok, CME} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CMG} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CMI} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CMK} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CMM} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CMO} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, {CME, CMG, CMI, CMK, CMM, CMO}} | - {error, list(decode_error())}). -tuple6(Decode1, Decode2, Decode3, Decode4, Decode5, Decode6) -> - fun(Value) -> - gleam@result:'try'( - gleam_stdlib:decode_tuple6(Value), - fun(_use0) -> - {A, B, C, D, E, F} = _use0, - case {Decode1(A), - Decode2(B), - Decode3(C), - Decode4(D), - Decode5(E), - Decode6(F)} of - {{ok, A@1}, - {ok, B@1}, - {ok, C@1}, - {ok, D@1}, - {ok, E@1}, - {ok, F@1}} -> - {ok, {A@1, B@1, C@1, D@1, E@1, F@1}}; - - {A@2, B@2, C@2, D@2, E@2, F@2} -> - _pipe = tuple_errors(A@2, <<"0"/utf8>>), - _pipe@1 = lists:append( - _pipe, - tuple_errors(B@2, <<"1"/utf8>>) - ), - _pipe@2 = lists:append( - _pipe@1, - tuple_errors(C@2, <<"2"/utf8>>) - ), - _pipe@3 = lists:append( - _pipe@2, - tuple_errors(D@2, <<"3"/utf8>>) - ), - _pipe@4 = lists:append( - _pipe@3, - tuple_errors(E@2, <<"4"/utf8>>) - ), - _pipe@5 = lists:append( - _pipe@4, - tuple_errors(F@2, <<"5"/utf8>>) - ), - {error, _pipe@5} - end - end - ) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 968). --spec dict( - fun((dynamic_()) -> {ok, CMR} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CMT} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, gleam@dict:dict(CMR, CMT)} | - {error, list(decode_error())}). -dict(Key_type, Value_type) -> - fun(Value) -> - gleam@result:'try'( - gleam_stdlib:decode_map(Value), - fun(Map) -> - gleam@result:'try'( - begin - _pipe = Map, - _pipe@1 = maps:to_list(_pipe), - gleam@list:try_map( - _pipe@1, - fun(Pair) -> - {K, V} = Pair, - gleam@result:'try'( - begin - _pipe@2 = Key_type(K), - map_errors( - _pipe@2, - fun(_capture) -> - push_path( - _capture, - <<"keys"/utf8>> - ) - end - ) - end, - fun(K@1) -> - gleam@result:'try'( - begin - _pipe@3 = Value_type(V), - map_errors( - _pipe@3, - fun(_capture@1) -> - push_path( - _capture@1, - <<"values"/utf8>> - ) - end - ) - end, - fun(V@1) -> {ok, {K@1, V@1}} end - ) - end - ) - end - ) - end, - fun(Pairs) -> {ok, maps:from_list(Pairs)} end - ) - end - ) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 1082). --spec decode2( - fun((CNK, CNL) -> CNM), - fun((dynamic_()) -> {ok, CNK} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CNL} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, CNM} | {error, list(decode_error())}). -decode2(Constructor, T1, T2) -> - fun(Value) -> case {T1(Value), T2(Value)} of - {{ok, A}, {ok, B}} -> - {ok, Constructor(A, B)}; - - {A@1, B@1} -> - {error, gleam@list:flatten([all_errors(A@1), all_errors(B@1)])} - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 1114). --spec decode3( - fun((CNQ, CNR, CNS) -> CNT), - fun((dynamic_()) -> {ok, CNQ} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CNR} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CNS} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, CNT} | {error, list(decode_error())}). -decode3(Constructor, T1, T2, T3) -> - fun(Value) -> case {T1(Value), T2(Value), T3(Value)} of - {{ok, A}, {ok, B}, {ok, C}} -> - {ok, Constructor(A, B, C)}; - - {A@1, B@1, C@1} -> - {error, - gleam@list:flatten( - [all_errors(A@1), all_errors(B@1), all_errors(C@1)] - )} - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 1160). --spec decode4( - fun((CNY, CNZ, COA, COB) -> COC), - fun((dynamic_()) -> {ok, CNY} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CNZ} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, COA} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, COB} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, COC} | {error, list(decode_error())}). -decode4(Constructor, T1, T2, T3, T4) -> - fun(X) -> case {T1(X), T2(X), T3(X), T4(X)} of - {{ok, A}, {ok, B}, {ok, C}, {ok, D}} -> - {ok, Constructor(A, B, C, D)}; - - {A@1, B@1, C@1, D@1} -> - {error, - gleam@list:flatten( - [all_errors(A@1), - all_errors(B@1), - all_errors(C@1), - all_errors(D@1)] - )} - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 1216). --spec decode5( - fun((COI, COJ, COK, COL, COM) -> CON), - fun((dynamic_()) -> {ok, COI} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, COJ} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, COK} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, COL} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, COM} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, CON} | {error, list(decode_error())}). -decode5(Constructor, T1, T2, T3, T4, T5) -> - fun(X) -> case {T1(X), T2(X), T3(X), T4(X), T5(X)} of - {{ok, A}, {ok, B}, {ok, C}, {ok, D}, {ok, E}} -> - {ok, Constructor(A, B, C, D, E)}; - - {A@1, B@1, C@1, D@1, E@1} -> - {error, - gleam@list:flatten( - [all_errors(A@1), - all_errors(B@1), - all_errors(C@1), - all_errors(D@1), - all_errors(E@1)] - )} - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 1276). --spec decode6( - fun((COU, COV, COW, COX, COY, COZ) -> CPA), - fun((dynamic_()) -> {ok, COU} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, COV} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, COW} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, COX} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, COY} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, COZ} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, CPA} | {error, list(decode_error())}). -decode6(Constructor, T1, T2, T3, T4, T5, T6) -> - fun(X) -> case {T1(X), T2(X), T3(X), T4(X), T5(X), T6(X)} of - {{ok, A}, {ok, B}, {ok, C}, {ok, D}, {ok, E}, {ok, F}} -> - {ok, Constructor(A, B, C, D, E, F)}; - - {A@1, B@1, C@1, D@1, E@1, F@1} -> - {error, - gleam@list:flatten( - [all_errors(A@1), - all_errors(B@1), - all_errors(C@1), - all_errors(D@1), - all_errors(E@1), - all_errors(F@1)] - )} - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 1341). --spec decode7( - fun((CPI, CPJ, CPK, CPL, CPM, CPN, CPO) -> CPP), - fun((dynamic_()) -> {ok, CPI} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CPJ} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CPK} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CPL} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CPM} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CPN} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CPO} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, CPP} | {error, list(decode_error())}). -decode7(Constructor, T1, T2, T3, T4, T5, T6, T7) -> - fun(X) -> case {T1(X), T2(X), T3(X), T4(X), T5(X), T6(X), T7(X)} of - {{ok, A}, {ok, B}, {ok, C}, {ok, D}, {ok, E}, {ok, F}, {ok, G}} -> - {ok, Constructor(A, B, C, D, E, F, G)}; - - {A@1, B@1, C@1, D@1, E@1, F@1, G@1} -> - {error, - gleam@list:flatten( - [all_errors(A@1), - all_errors(B@1), - all_errors(C@1), - all_errors(D@1), - all_errors(E@1), - all_errors(F@1), - all_errors(G@1)] - )} - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 1410). --spec decode8( - fun((CPY, CPZ, CQA, CQB, CQC, CQD, CQE, CQF) -> CQG), - fun((dynamic_()) -> {ok, CPY} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CPZ} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQA} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQB} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQC} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQD} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQE} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQF} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, CQG} | {error, list(decode_error())}). -decode8(Constructor, T1, T2, T3, T4, T5, T6, T7, T8) -> - fun(X) -> case {T1(X), T2(X), T3(X), T4(X), T5(X), T6(X), T7(X), T8(X)} of - {{ok, A}, - {ok, B}, - {ok, C}, - {ok, D}, - {ok, E}, - {ok, F}, - {ok, G}, - {ok, H}} -> - {ok, Constructor(A, B, C, D, E, F, G, H)}; - - {A@1, B@1, C@1, D@1, E@1, F@1, G@1, H@1} -> - {error, - gleam@list:flatten( - [all_errors(A@1), - all_errors(B@1), - all_errors(C@1), - all_errors(D@1), - all_errors(E@1), - all_errors(F@1), - all_errors(G@1), - all_errors(H@1)] - )} - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/dynamic.gleam", 1483). --spec decode9( - fun((CQQ, CQR, CQS, CQT, CQU, CQV, CQW, CQX, CQY) -> CQZ), - fun((dynamic_()) -> {ok, CQQ} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQR} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQS} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQT} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQU} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQV} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQW} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQX} | {error, list(decode_error())}), - fun((dynamic_()) -> {ok, CQY} | {error, list(decode_error())}) -) -> fun((dynamic_()) -> {ok, CQZ} | {error, list(decode_error())}). -decode9(Constructor, T1, T2, T3, T4, T5, T6, T7, T8, T9) -> - fun(X) -> - case {T1(X), T2(X), T3(X), T4(X), T5(X), T6(X), T7(X), T8(X), T9(X)} of - {{ok, A}, - {ok, B}, - {ok, C}, - {ok, D}, - {ok, E}, - {ok, F}, - {ok, G}, - {ok, H}, - {ok, I}} -> - {ok, Constructor(A, B, C, D, E, F, G, H, I)}; - - {A@1, B@1, C@1, D@1, E@1, F@1, G@1, H@1, I@1} -> - {error, - gleam@list:flatten( - [all_errors(A@1), - all_errors(B@1), - all_errors(C@1), - all_errors(D@1), - all_errors(E@1), - all_errors(F@1), - all_errors(G@1), - all_errors(H@1), - all_errors(I@1)] - )} - end - end. diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@float.erl b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@float.erl deleted file mode 100644 index 99936162837..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@float.erl +++ /dev/null @@ -1,231 +0,0 @@ --module(gleam@float). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([parse/1, to_string/1, compare/2, min/2, max/2, clamp/3, ceiling/1, floor/1, truncate/1, absolute_value/1, loosely_compare/3, loosely_equals/3, power/2, square_root/1, negate/1, round/1, to_precision/2, sum/1, product/1, random/0, modulo/2, divide/2, add/2, multiply/2, subtract/2]). - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 32). --spec parse(binary()) -> {ok, float()} | {error, nil}. -parse(String) -> - gleam_stdlib:parse_float(String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 49). --spec to_string(float()) -> binary(). -to_string(X) -> - gleam_stdlib:float_to_string(X). - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 86). --spec compare(float(), float()) -> gleam@order:order(). -compare(A, B) -> - case A =:= B of - true -> - eq; - - false -> - case A < B of - true -> - lt; - - false -> - gt - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 167). --spec min(float(), float()) -> float(). -min(A, B) -> - case A < B of - true -> - A; - - false -> - B - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 183). --spec max(float(), float()) -> float(). -max(A, B) -> - case A > B of - true -> - A; - - false -> - B - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 66). --spec clamp(float(), float(), float()) -> float(). -clamp(X, Min_bound, Max_bound) -> - _pipe = X, - _pipe@1 = min(_pipe, Max_bound), - max(_pipe@1, Min_bound). - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 199). --spec ceiling(float()) -> float(). -ceiling(X) -> - math:ceil(X). - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 216). --spec floor(float()) -> float(). -floor(X) -> - math:floor(X). - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 262). --spec truncate(float()) -> integer(). -truncate(X) -> - erlang:trunc(X). - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 310). --spec absolute_value(float()) -> float(). -absolute_value(X) -> - case X >= +0.0 of - true -> - X; - - _ -> - +0.0 - X - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 116). --spec loosely_compare(float(), float(), float()) -> gleam@order:order(). -loosely_compare(A, B, Tolerance) -> - Difference = absolute_value(A - B), - case Difference =< Tolerance of - true -> - eq; - - false -> - compare(A, B) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 149). --spec loosely_equals(float(), float(), float()) -> boolean(). -loosely_equals(A, B, Tolerance) -> - Difference = absolute_value(A - B), - Difference =< Tolerance. - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 347). --spec power(float(), float()) -> {ok, float()} | {error, nil}. -power(Base, Exponent) -> - Fractional = (ceiling(Exponent) - Exponent) > +0.0, - case ((Base < +0.0) andalso Fractional) orelse ((Base =:= +0.0) andalso (Exponent - < +0.0)) of - true -> - {error, nil}; - - false -> - {ok, math:pow(Base, Exponent)} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 379). --spec square_root(float()) -> {ok, float()} | {error, nil}. -square_root(X) -> - power(X, 0.5). - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 392). --spec negate(float()) -> float(). -negate(X) -> - -1.0 * X. - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 238). --spec round(float()) -> integer(). -round(X) -> - erlang:round(X). - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 287). --spec to_precision(float(), integer()) -> float(). -to_precision(X, Precision) -> - Factor = math:pow(10.0, erlang:float(- Precision)), - erlang:float(round(case Factor of - +0.0 -> +0.0; - -0.0 -> -0.0; - Gleam@denominator -> X / Gleam@denominator - end)) * Factor. - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 410). --spec do_sum(list(float()), float()) -> float(). -do_sum(Numbers, Initial) -> - case Numbers of - [] -> - Initial; - - [X | Rest] -> - do_sum(Rest, X + Initial) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 405). --spec sum(list(float())) -> float(). -sum(Numbers) -> - _pipe = Numbers, - do_sum(_pipe, +0.0). - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 433). --spec do_product(list(float()), float()) -> float(). -do_product(Numbers, Initial) -> - case Numbers of - [] -> - Initial; - - [X | Rest] -> - do_product(Rest, X * Initial) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 426). --spec product(list(float())) -> float(). -product(Numbers) -> - case Numbers of - [] -> - 1.0; - - _ -> - do_product(Numbers, 1.0) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 455). --spec random() -> float(). -random() -> - rand:uniform(). - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 484). --spec modulo(float(), float()) -> {ok, float()} | {error, nil}. -modulo(Dividend, Divisor) -> - case Divisor of - +0.0 -> - {error, nil}; - - _ -> - {ok, Dividend - (floor(case Divisor of - +0.0 -> +0.0; - -0.0 -> -0.0; - Gleam@denominator -> Dividend / Gleam@denominator - end) * Divisor)} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 505). --spec divide(float(), float()) -> {ok, float()} | {error, nil}. -divide(A, B) -> - case B of - +0.0 -> - {error, nil}; - - B@1 -> - {ok, case B@1 of - +0.0 -> +0.0; - -0.0 -> -0.0; - Gleam@denominator -> A / Gleam@denominator - end} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 536). --spec add(float(), float()) -> float(). -add(A, B) -> - A + B. - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 564). --spec multiply(float(), float()) -> float(). -multiply(A, B) -> - A * B. - --file("/Users/louis/src/gleam/stdlib/src/gleam/float.gleam", 597). --spec subtract(float(), float()) -> float(). -subtract(A, B) -> - A - B. diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@function.erl b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@function.erl deleted file mode 100644 index e3895743459..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@function.erl +++ /dev/null @@ -1,80 +0,0 @@ --module(gleam@function). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([compose/2, curry2/1, curry3/1, curry4/1, curry5/1, curry6/1, flip/1, identity/1, constant/1, tap/2, apply1/2, apply2/3, apply3/4]). - --file("/Users/louis/src/gleam/stdlib/src/gleam/function.gleam", 2). --spec compose(fun((DPR) -> DPS), fun((DPS) -> DPT)) -> fun((DPR) -> DPT). -compose(Fun1, Fun2) -> - fun(A) -> Fun2(Fun1(A)) end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/function.gleam", 7). --spec curry2(fun((DPU, DPV) -> DPW)) -> fun((DPU) -> fun((DPV) -> DPW)). -curry2(Fun) -> - fun(A) -> fun(B) -> Fun(A, B) end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/function.gleam", 12). --spec curry3(fun((DPY, DPZ, DQA) -> DQB)) -> fun((DPY) -> fun((DPZ) -> fun((DQA) -> DQB))). -curry3(Fun) -> - fun(A) -> fun(B) -> fun(C) -> Fun(A, B, C) end end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/function.gleam", 17). --spec curry4(fun((DQD, DQE, DQF, DQG) -> DQH)) -> fun((DQD) -> fun((DQE) -> fun((DQF) -> fun((DQG) -> DQH)))). -curry4(Fun) -> - fun(A) -> fun(B) -> fun(C) -> fun(D) -> Fun(A, B, C, D) end end end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/function.gleam", 22). --spec curry5(fun((DQJ, DQK, DQL, DQM, DQN) -> DQO)) -> fun((DQJ) -> fun((DQK) -> fun((DQL) -> fun((DQM) -> fun((DQN) -> DQO))))). -curry5(Fun) -> - fun(A) -> - fun(B) -> - fun(C) -> fun(D) -> fun(E) -> Fun(A, B, C, D, E) end end end - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/function.gleam", 27). --spec curry6(fun((DQQ, DQR, DQS, DQT, DQU, DQV) -> DQW)) -> fun((DQQ) -> fun((DQR) -> fun((DQS) -> fun((DQT) -> fun((DQU) -> fun((DQV) -> DQW)))))). -curry6(Fun) -> - fun(A) -> - fun(B) -> - fun(C) -> - fun(D) -> fun(E) -> fun(F) -> Fun(A, B, C, D, E, F) end end end - end - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/function.gleam", 36). --spec flip(fun((DQY, DQZ) -> DRA)) -> fun((DQZ, DQY) -> DRA). -flip(Fun) -> - fun(B, A) -> Fun(A, B) end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/function.gleam", 42). --spec identity(DRB) -> DRB. -identity(X) -> - X. - --file("/Users/louis/src/gleam/stdlib/src/gleam/function.gleam", 47). --spec constant(DRC) -> fun((any()) -> DRC). -constant(Value) -> - fun(_) -> Value end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/function.gleam", 56). --spec tap(DRE, fun((DRE) -> any())) -> DRE. -tap(Arg, Effect) -> - Effect(Arg), - Arg. - --file("/Users/louis/src/gleam/stdlib/src/gleam/function.gleam", 62). --spec apply1(fun((DRG) -> DRH), DRG) -> DRH. -apply1(Fun, Arg1) -> - Fun(Arg1). - --file("/Users/louis/src/gleam/stdlib/src/gleam/function.gleam", 67). --spec apply2(fun((DRI, DRJ) -> DRK), DRI, DRJ) -> DRK. -apply2(Fun, Arg1, Arg2) -> - Fun(Arg1, Arg2). - --file("/Users/louis/src/gleam/stdlib/src/gleam/function.gleam", 72). --spec apply3(fun((DRL, DRM, DRN) -> DRO), DRL, DRM, DRN) -> DRO. -apply3(Fun, Arg1, Arg2, Arg3) -> - Fun(Arg1, Arg2, Arg3). diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@int.erl b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@int.erl deleted file mode 100644 index c1ca0dabbb7..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@int.erl +++ /dev/null @@ -1,367 +0,0 @@ --module(gleam@int). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([absolute_value/1, parse/1, base_parse/2, to_string/1, to_base_string/2, to_base2/1, to_base8/1, to_base16/1, to_base36/1, to_float/1, power/2, square_root/1, compare/2, min/2, max/2, clamp/3, is_even/1, is_odd/1, negate/1, sum/1, product/1, digits/2, undigits/2, random/1, divide/2, remainder/2, modulo/2, floor_divide/2, add/2, multiply/2, subtract/2, bitwise_and/2, bitwise_not/1, bitwise_or/2, bitwise_exclusive_or/2, bitwise_shift_left/2, bitwise_shift_right/2]). - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 30). --spec absolute_value(integer()) -> integer(). -absolute_value(X) -> - case X >= 0 of - true -> - X; - - false -> - X * -1 - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 107). --spec parse(binary()) -> {ok, integer()} | {error, nil}. -parse(String) -> - gleam_stdlib:parse_int(String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 145). --spec base_parse(binary(), integer()) -> {ok, integer()} | {error, nil}. -base_parse(String, Base) -> - case (Base >= 2) andalso (Base =< 36) of - true -> - gleam_stdlib:int_from_base_string(String, Base); - - false -> - {error, nil} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 165). --spec to_string(integer()) -> binary(). -to_string(X) -> - erlang:integer_to_binary(X). - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 204). --spec to_base_string(integer(), integer()) -> {ok, binary()} | {error, nil}. -to_base_string(X, Base) -> - case (Base >= 2) andalso (Base =< 36) of - true -> - {ok, erlang:integer_to_binary(X, Base)}; - - false -> - {error, nil} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 224). --spec to_base2(integer()) -> binary(). -to_base2(X) -> - erlang:integer_to_binary(X, 2). - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 237). --spec to_base8(integer()) -> binary(). -to_base8(X) -> - erlang:integer_to_binary(X, 8). - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 250). --spec to_base16(integer()) -> binary(). -to_base16(X) -> - erlang:integer_to_binary(X, 16). - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 263). --spec to_base36(integer()) -> binary(). -to_base36(X) -> - erlang:integer_to_binary(X, 36). - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 286). --spec to_float(integer()) -> float(). -to_float(X) -> - erlang:float(X). - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 67). --spec power(integer(), float()) -> {ok, float()} | {error, nil}. -power(Base, Exponent) -> - _pipe = Base, - _pipe@1 = to_float(_pipe), - gleam@float:power(_pipe@1, Exponent). - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 87). --spec square_root(integer()) -> {ok, float()} | {error, nil}. -square_root(X) -> - _pipe = X, - _pipe@1 = to_float(_pipe), - gleam@float:square_root(_pipe@1). - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 328). --spec compare(integer(), integer()) -> gleam@order:order(). -compare(A, B) -> - case A =:= B of - true -> - eq; - - false -> - case A < B of - true -> - lt; - - false -> - gt - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 348). --spec min(integer(), integer()) -> integer(). -min(A, B) -> - case A < B of - true -> - A; - - false -> - B - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 364). --spec max(integer(), integer()) -> integer(). -max(A, B) -> - case A > B of - true -> - A; - - false -> - B - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 303). --spec clamp(integer(), integer(), integer()) -> integer(). -clamp(X, Min_bound, Max_bound) -> - _pipe = X, - _pipe@1 = min(_pipe, Max_bound), - max(_pipe@1, Min_bound). - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 385). --spec is_even(integer()) -> boolean(). -is_even(X) -> - (X rem 2) =:= 0. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 403). --spec is_odd(integer()) -> boolean(). -is_odd(X) -> - (X rem 2) /= 0. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 416). --spec negate(integer()) -> integer(). -negate(X) -> - -1 * X. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 434). --spec do_sum(list(integer()), integer()) -> integer(). -do_sum(Numbers, Initial) -> - case Numbers of - [] -> - Initial; - - [X | Rest] -> - do_sum(Rest, X + Initial) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 429). --spec sum(list(integer())) -> integer(). -sum(Numbers) -> - _pipe = Numbers, - do_sum(_pipe, 0). - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 457). --spec do_product(list(integer()), integer()) -> integer(). -do_product(Numbers, Initial) -> - case Numbers of - [] -> - Initial; - - [X | Rest] -> - do_product(Rest, X * Initial) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 450). --spec product(list(integer())) -> integer(). -product(Numbers) -> - case Numbers of - [] -> - 1; - - _ -> - do_product(Numbers, 1) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 486). --spec do_digits(integer(), integer(), list(integer())) -> list(integer()). -do_digits(X, Base, Acc) -> - case absolute_value(X) < Base of - true -> - [X | Acc]; - - false -> - do_digits(case Base of - 0 -> 0; - Gleam@denominator -> X div Gleam@denominator - end, Base, [case Base of - 0 -> 0; - Gleam@denominator@1 -> X rem Gleam@denominator@1 - end | Acc]) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 479). --spec digits(integer(), integer()) -> {ok, list(integer())} | {error, nil}. -digits(X, Base) -> - case Base < 2 of - true -> - {error, nil}; - - false -> - {ok, do_digits(X, Base, [])} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 520). --spec do_undigits(list(integer()), integer(), integer()) -> {ok, integer()} | - {error, nil}. -do_undigits(Numbers, Base, Acc) -> - case Numbers of - [] -> - {ok, Acc}; - - [Digit | _] when Digit >= Base -> - {error, nil}; - - [Digit@1 | Rest] -> - do_undigits(Rest, Base, (Acc * Base) + Digit@1) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 513). --spec undigits(list(integer()), integer()) -> {ok, integer()} | {error, nil}. -undigits(Numbers, Base) -> - case Base < 2 of - true -> - {error, nil}; - - false -> - do_undigits(Numbers, Base, 0) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 549). --spec random(integer()) -> integer(). -random(Max) -> - _pipe = (rand:uniform() * to_float(Max)), - _pipe@1 = gleam@float:floor(_pipe), - gleam@float:round(_pipe@1). - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 582). --spec divide(integer(), integer()) -> {ok, integer()} | {error, nil}. -divide(Dividend, Divisor) -> - case Divisor of - 0 -> - {error, nil}; - - Divisor@1 -> - {ok, case Divisor@1 of - 0 -> 0; - Gleam@denominator -> Dividend div Gleam@denominator - end} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 634). --spec remainder(integer(), integer()) -> {ok, integer()} | {error, nil}. -remainder(Dividend, Divisor) -> - case Divisor of - 0 -> - {error, nil}; - - Divisor@1 -> - {ok, case Divisor@1 of - 0 -> 0; - Gleam@denominator -> Dividend rem Gleam@denominator - end} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 676). --spec modulo(integer(), integer()) -> {ok, integer()} | {error, nil}. -modulo(Dividend, Divisor) -> - case Divisor of - 0 -> - {error, nil}; - - _ -> - Remainder = case Divisor of - 0 -> 0; - Gleam@denominator -> Dividend rem Gleam@denominator - end, - case (Remainder * Divisor) < 0 of - true -> - {ok, Remainder + Divisor}; - - false -> - {ok, Remainder} - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 720). --spec floor_divide(integer(), integer()) -> {ok, integer()} | {error, nil}. -floor_divide(Dividend, Divisor) -> - case Divisor of - 0 -> - {error, nil}; - - Divisor@1 -> - case ((Dividend * Divisor@1) < 0) andalso ((case Divisor@1 of - 0 -> 0; - Gleam@denominator -> Dividend rem Gleam@denominator - end) /= 0) of - true -> - {ok, (case Divisor@1 of - 0 -> 0; - Gleam@denominator@1 -> Dividend div Gleam@denominator@1 - end) - 1}; - - false -> - {ok, case Divisor@1 of - 0 -> 0; - Gleam@denominator@2 -> Dividend div Gleam@denominator@2 - end} - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 754). --spec add(integer(), integer()) -> integer(). -add(A, B) -> - A + B. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 782). --spec multiply(integer(), integer()) -> integer(). -multiply(A, B) -> - A * B. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 815). --spec subtract(integer(), integer()) -> integer(). -subtract(A, B) -> - A - B. - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 827). --spec bitwise_and(integer(), integer()) -> integer(). -bitwise_and(X, Y) -> - erlang:'band'(X, Y). - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 837). --spec bitwise_not(integer()) -> integer(). -bitwise_not(X) -> - erlang:'bnot'(X). - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 847). --spec bitwise_or(integer(), integer()) -> integer(). -bitwise_or(X, Y) -> - erlang:'bor'(X, Y). - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 857). --spec bitwise_exclusive_or(integer(), integer()) -> integer(). -bitwise_exclusive_or(X, Y) -> - erlang:'bxor'(X, Y). - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 867). --spec bitwise_shift_left(integer(), integer()) -> integer(). -bitwise_shift_left(X, Y) -> - erlang:'bsl'(X, Y). - --file("/Users/louis/src/gleam/stdlib/src/gleam/int.gleam", 877). --spec bitwise_shift_right(integer(), integer()) -> integer(). -bitwise_shift_right(X, Y) -> - erlang:'bsr'(X, Y). diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@io.erl b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@io.erl deleted file mode 100644 index 43ca590a484..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@io.erl +++ /dev/null @@ -1,32 +0,0 @@ --module(gleam@io). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([print/1, print_error/1, println/1, println_error/1, debug/1]). - --file("/Users/louis/src/gleam/stdlib/src/gleam/io.gleam", 15). --spec print(binary()) -> nil. -print(String) -> - gleam_stdlib:print(String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/io.gleam", 35). --spec print_error(binary()) -> nil. -print_error(String) -> - gleam_stdlib:print_error(String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/io.gleam", 53). --spec println(binary()) -> nil. -println(String) -> - gleam_stdlib:println(String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/io.gleam", 71). --spec println_error(binary()) -> nil. -println_error(String) -> - gleam_stdlib:println_error(String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/io.gleam", 108). --spec debug(DSO) -> DSO. -debug(Term) -> - _pipe = Term, - _pipe@1 = gleam@string:inspect(_pipe), - gleam_stdlib:println_error(_pipe@1), - Term. diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@iterator.erl b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@iterator.erl deleted file mode 100644 index e903db771c3..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@iterator.erl +++ /dev/null @@ -1,873 +0,0 @@ --module(gleam@iterator). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([unfold/2, repeatedly/1, repeat/1, from_list/1, transform/3, fold/3, run/1, to_list/1, step/1, take/2, drop/2, map/2, map2/3, append/2, flatten/1, concat/1, flat_map/2, filter/2, filter_map/2, cycle/1, find/2, find_map/2, index/1, iterate/2, take_while/2, drop_while/2, scan/3, zip/2, chunk/2, sized_chunk/2, intersperse/2, any/2, all/2, group/2, reduce/2, last/1, empty/0, once/1, range/2, single/1, interleave/2, fold_until/3, try_fold/3, first/1, at/2, length/1, each/2, yield/2]). --export_type([action/1, iterator/1, step/2, chunk/2, sized_chunk/1]). - --type action(DSY) :: stop | {continue, DSY, fun(() -> action(DSY))}. - --opaque iterator(DSZ) :: {iterator, fun(() -> action(DSZ))}. - --type step(DTA, DTB) :: {next, DTA, DTB} | done. - --type chunk(DTC, DTD) :: {another_by, - list(DTC), - DTD, - DTC, - fun(() -> action(DTC))} | - {last_by, list(DTC)}. - --type sized_chunk(DTE) :: {another, list(DTE), fun(() -> action(DTE))} | - {last, list(DTE)} | - no_more. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 37). --spec stop() -> action(any()). -stop() -> - stop. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 42). --spec do_unfold(DTH, fun((DTH) -> step(DTI, DTH))) -> fun(() -> action(DTI)). -do_unfold(Initial, F) -> - fun() -> case F(Initial) of - {next, X, Acc} -> - {continue, X, do_unfold(Acc, F)}; - - done -> - stop - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 75). --spec unfold(DTM, fun((DTM) -> step(DTN, DTM))) -> iterator(DTN). -unfold(Initial, F) -> - _pipe = Initial, - _pipe@1 = do_unfold(_pipe, F), - {iterator, _pipe@1}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 94). --spec repeatedly(fun(() -> DTR)) -> iterator(DTR). -repeatedly(F) -> - unfold(nil, fun(_) -> {next, F(), nil} end). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 109). --spec repeat(DTT) -> iterator(DTT). -repeat(X) -> - repeatedly(fun() -> X end). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 123). --spec from_list(list(DTV)) -> iterator(DTV). -from_list(List) -> - Yield = fun(Acc) -> case Acc of - [] -> - done; - - [Head | Tail] -> - {next, Head, Tail} - end end, - unfold(List, Yield). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 134). --spec do_transform( - fun(() -> action(DTY)), - DUA, - fun((DUA, DTY) -> step(DUB, DUA)) -) -> fun(() -> action(DUB)). -do_transform(Continuation, State, F) -> - fun() -> case Continuation() of - stop -> - stop; - - {continue, El, Next} -> - case F(State, El) of - done -> - stop; - - {next, Yield, Next_state} -> - {continue, Yield, do_transform(Next, Next_state, F)} - end - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 169). --spec transform(iterator(DUF), DUH, fun((DUH, DUF) -> step(DUI, DUH))) -> iterator(DUI). -transform(Iterator, Initial, F) -> - _pipe = do_transform(erlang:element(2, Iterator), Initial, F), - {iterator, _pipe}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 178). --spec do_fold(fun(() -> action(DUM)), fun((DUO, DUM) -> DUO), DUO) -> DUO. -do_fold(Continuation, F, Accumulator) -> - case Continuation() of - {continue, Elem, Next} -> - do_fold(Next, F, F(Accumulator, Elem)); - - stop -> - Accumulator - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 206). --spec fold(iterator(DUP), DUR, fun((DUR, DUP) -> DUR)) -> DUR. -fold(Iterator, Initial, F) -> - _pipe = erlang:element(2, Iterator), - do_fold(_pipe, F, Initial). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 220). --spec run(iterator(any())) -> nil. -run(Iterator) -> - fold(Iterator, nil, fun(_, _) -> nil end). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 238). --spec to_list(iterator(DUU)) -> list(DUU). -to_list(Iterator) -> - _pipe = Iterator, - _pipe@1 = fold(_pipe, [], fun(Acc, E) -> [E | Acc] end), - lists:reverse(_pipe@1). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 266). --spec step(iterator(DUX)) -> step(DUX, iterator(DUX)). -step(Iterator) -> - case (erlang:element(2, Iterator))() of - stop -> - done; - - {continue, E, A} -> - {next, E, {iterator, A}} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 273). --spec do_take(fun(() -> action(DVC)), integer()) -> fun(() -> action(DVC)). -do_take(Continuation, Desired) -> - fun() -> case Desired > 0 of - false -> - stop; - - true -> - case Continuation() of - stop -> - stop; - - {continue, E, Next} -> - {continue, E, do_take(Next, Desired - 1)} - end - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 306). --spec take(iterator(DVF), integer()) -> iterator(DVF). -take(Iterator, Desired) -> - _pipe = erlang:element(2, Iterator), - _pipe@1 = do_take(_pipe, Desired), - {iterator, _pipe@1}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 312). --spec do_drop(fun(() -> action(DVI)), integer()) -> action(DVI). -do_drop(Continuation, Desired) -> - case Continuation() of - stop -> - stop; - - {continue, E, Next} -> - case Desired > 0 of - true -> - do_drop(Next, Desired - 1); - - false -> - {continue, E, Next} - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 348). --spec drop(iterator(DVL), integer()) -> iterator(DVL). -drop(Iterator, Desired) -> - _pipe = fun() -> do_drop(erlang:element(2, Iterator), Desired) end, - {iterator, _pipe}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 353). --spec do_map(fun(() -> action(DVO)), fun((DVO) -> DVQ)) -> fun(() -> action(DVQ)). -do_map(Continuation, F) -> - fun() -> case Continuation() of - stop -> - stop; - - {continue, E, Continuation@1} -> - {continue, F(E), do_map(Continuation@1, F)} - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 379). --spec map(iterator(DVS), fun((DVS) -> DVU)) -> iterator(DVU). -map(Iterator, F) -> - _pipe = erlang:element(2, Iterator), - _pipe@1 = do_map(_pipe, F), - {iterator, _pipe@1}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 385). --spec do_map2( - fun(() -> action(DVW)), - fun(() -> action(DVY)), - fun((DVW, DVY) -> DWA) -) -> fun(() -> action(DWA)). -do_map2(Continuation1, Continuation2, Fun) -> - fun() -> case Continuation1() of - stop -> - stop; - - {continue, A, Next_a} -> - case Continuation2() of - stop -> - stop; - - {continue, B, Next_b} -> - {continue, Fun(A, B), do_map2(Next_a, Next_b, Fun)} - end - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 426). --spec map2(iterator(DWC), iterator(DWE), fun((DWC, DWE) -> DWG)) -> iterator(DWG). -map2(Iterator1, Iterator2, Fun) -> - _pipe = do_map2( - erlang:element(2, Iterator1), - erlang:element(2, Iterator2), - Fun - ), - {iterator, _pipe}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 435). --spec do_append(fun(() -> action(DWI)), fun(() -> action(DWI))) -> action(DWI). -do_append(First, Second) -> - case First() of - {continue, E, First@1} -> - {continue, E, fun() -> do_append(First@1, Second) end}; - - stop -> - Second() - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 456). --spec append(iterator(DWM), iterator(DWM)) -> iterator(DWM). -append(First, Second) -> - _pipe = fun() -> - do_append(erlang:element(2, First), erlang:element(2, Second)) - end, - {iterator, _pipe}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 461). --spec do_flatten(fun(() -> action(iterator(DWQ)))) -> action(DWQ). -do_flatten(Flattened) -> - case Flattened() of - stop -> - stop; - - {continue, It, Next_iterator} -> - do_append( - erlang:element(2, It), - fun() -> do_flatten(Next_iterator) end - ) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 484). --spec flatten(iterator(iterator(DWU))) -> iterator(DWU). -flatten(Iterator) -> - _pipe = fun() -> do_flatten(erlang:element(2, Iterator)) end, - {iterator, _pipe}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 504). --spec concat(list(iterator(DWY))) -> iterator(DWY). -concat(Iterators) -> - flatten(from_list(Iterators)). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 526). --spec flat_map(iterator(DXC), fun((DXC) -> iterator(DXE))) -> iterator(DXE). -flat_map(Iterator, F) -> - _pipe = Iterator, - _pipe@1 = map(_pipe, F), - flatten(_pipe@1). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 535). --spec do_filter(fun(() -> action(DXH)), fun((DXH) -> boolean())) -> action(DXH). -do_filter(Continuation, Predicate) -> - case Continuation() of - stop -> - stop; - - {continue, E, Iterator} -> - case Predicate(E) of - true -> - {continue, E, fun() -> do_filter(Iterator, Predicate) end}; - - false -> - do_filter(Iterator, Predicate) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 568). --spec filter(iterator(DXK), fun((DXK) -> boolean())) -> iterator(DXK). -filter(Iterator, Predicate) -> - _pipe = fun() -> do_filter(erlang:element(2, Iterator), Predicate) end, - {iterator, _pipe}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 576). --spec do_filter_map( - fun(() -> action(DXN)), - fun((DXN) -> {ok, DXP} | {error, any()}) -) -> action(DXP). -do_filter_map(Continuation, F) -> - case Continuation() of - stop -> - stop; - - {continue, E, Next} -> - case F(E) of - {ok, E@1} -> - {continue, E@1, fun() -> do_filter_map(Next, F) end}; - - {error, _} -> - do_filter_map(Next, F) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 612). --spec filter_map(iterator(DXU), fun((DXU) -> {ok, DXW} | {error, any()})) -> iterator(DXW). -filter_map(Iterator, F) -> - _pipe = fun() -> do_filter_map(erlang:element(2, Iterator), F) end, - {iterator, _pipe}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 632). --spec cycle(iterator(DYB)) -> iterator(DYB). -cycle(Iterator) -> - _pipe = repeat(Iterator), - flatten(_pipe). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 678). --spec do_find(fun(() -> action(DYF)), fun((DYF) -> boolean())) -> {ok, DYF} | - {error, nil}. -do_find(Continuation, F) -> - case Continuation() of - stop -> - {error, nil}; - - {continue, E, Next} -> - case F(E) of - true -> - {ok, E}; - - false -> - do_find(Next, F) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 712). --spec find(iterator(DYJ), fun((DYJ) -> boolean())) -> {ok, DYJ} | {error, nil}. -find(Haystack, Is_desired) -> - _pipe = erlang:element(2, Haystack), - do_find(_pipe, Is_desired). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 720). --spec do_find_map( - fun(() -> action(DYN)), - fun((DYN) -> {ok, DYP} | {error, any()}) -) -> {ok, DYP} | {error, nil}. -do_find_map(Continuation, F) -> - case Continuation() of - stop -> - {error, nil}; - - {continue, E, Next} -> - case F(E) of - {ok, E@1} -> - {ok, E@1}; - - {error, _} -> - do_find_map(Next, F) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 757). --spec find_map(iterator(DYV), fun((DYV) -> {ok, DYX} | {error, any()})) -> {ok, - DYX} | - {error, nil}. -find_map(Haystack, Is_desired) -> - _pipe = erlang:element(2, Haystack), - do_find_map(_pipe, Is_desired). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 765). --spec do_index(fun(() -> action(DZD)), integer()) -> fun(() -> action({DZD, - integer()})). -do_index(Continuation, Next) -> - fun() -> case Continuation() of - stop -> - stop; - - {continue, E, Continuation@1} -> - {continue, {E, Next}, do_index(Continuation@1, Next + 1)} - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 787). --spec index(iterator(DZG)) -> iterator({DZG, integer()}). -index(Iterator) -> - _pipe = erlang:element(2, Iterator), - _pipe@1 = do_index(_pipe, 0), - {iterator, _pipe@1}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 802). --spec iterate(DZJ, fun((DZJ) -> DZJ)) -> iterator(DZJ). -iterate(Initial, F) -> - unfold(Initial, fun(Element) -> {next, Element, F(Element)} end). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 809). --spec do_take_while(fun(() -> action(DZL)), fun((DZL) -> boolean())) -> fun(() -> action(DZL)). -do_take_while(Continuation, Predicate) -> - fun() -> case Continuation() of - stop -> - stop; - - {continue, E, Next} -> - case Predicate(E) of - false -> - stop; - - true -> - {continue, E, do_take_while(Next, Predicate)} - end - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 836). --spec take_while(iterator(DZO), fun((DZO) -> boolean())) -> iterator(DZO). -take_while(Iterator, Predicate) -> - _pipe = erlang:element(2, Iterator), - _pipe@1 = do_take_while(_pipe, Predicate), - {iterator, _pipe@1}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 845). --spec do_drop_while(fun(() -> action(DZR)), fun((DZR) -> boolean())) -> action(DZR). -do_drop_while(Continuation, Predicate) -> - case Continuation() of - stop -> - stop; - - {continue, E, Next} -> - case Predicate(E) of - false -> - {continue, E, Next}; - - true -> - do_drop_while(Next, Predicate) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 871). --spec drop_while(iterator(DZU), fun((DZU) -> boolean())) -> iterator(DZU). -drop_while(Iterator, Predicate) -> - _pipe = fun() -> do_drop_while(erlang:element(2, Iterator), Predicate) end, - {iterator, _pipe}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 879). --spec do_scan(fun(() -> action(DZX)), fun((DZZ, DZX) -> DZZ), DZZ) -> fun(() -> action(DZZ)). -do_scan(Continuation, F, Accumulator) -> - fun() -> case Continuation() of - stop -> - stop; - - {continue, El, Next} -> - Accumulated = F(Accumulator, El), - {continue, Accumulated, do_scan(Next, F, Accumulated)} - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 909). --spec scan(iterator(EAB), EAD, fun((EAD, EAB) -> EAD)) -> iterator(EAD). -scan(Iterator, Initial, F) -> - _pipe = erlang:element(2, Iterator), - _pipe@1 = do_scan(_pipe, F, Initial), - {iterator, _pipe@1}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 919). --spec do_zip(fun(() -> action(EAF)), fun(() -> action(EAH))) -> fun(() -> action({EAF, - EAH})). -do_zip(Left, Right) -> - fun() -> case Left() of - stop -> - stop; - - {continue, El_left, Next_left} -> - case Right() of - stop -> - stop; - - {continue, El_right, Next_right} -> - {continue, - {El_left, El_right}, - do_zip(Next_left, Next_right)} - end - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 948). --spec zip(iterator(EAK), iterator(EAM)) -> iterator({EAK, EAM}). -zip(Left, Right) -> - _pipe = do_zip(erlang:element(2, Left), erlang:element(2, Right)), - {iterator, _pipe}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 959). --spec next_chunk(fun(() -> action(EAP)), fun((EAP) -> EAR), EAR, list(EAP)) -> chunk(EAP, EAR). -next_chunk(Continuation, F, Previous_key, Current_chunk) -> - case Continuation() of - stop -> - {last_by, lists:reverse(Current_chunk)}; - - {continue, E, Next} -> - Key = F(E), - case Key =:= Previous_key of - true -> - next_chunk(Next, F, Key, [E | Current_chunk]); - - false -> - {another_by, lists:reverse(Current_chunk), Key, E, Next} - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 977). --spec do_chunk(fun(() -> action(EAV)), fun((EAV) -> EAX), EAX, EAV) -> action(list(EAV)). -do_chunk(Continuation, F, Previous_key, Previous_element) -> - case next_chunk(Continuation, F, Previous_key, [Previous_element]) of - {last_by, Chunk} -> - {continue, Chunk, fun stop/0}; - - {another_by, Chunk@1, Key, El, Next} -> - {continue, Chunk@1, fun() -> do_chunk(Next, F, Key, El) end} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1002). --spec chunk(iterator(EBA), fun((EBA) -> any())) -> iterator(list(EBA)). -chunk(Iterator, F) -> - _pipe = fun() -> case (erlang:element(2, Iterator))() of - stop -> - stop; - - {continue, E, Next} -> - do_chunk(Next, F, F(E), E) - end end, - {iterator, _pipe}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1022). --spec next_sized_chunk(fun(() -> action(EBF)), integer(), list(EBF)) -> sized_chunk(EBF). -next_sized_chunk(Continuation, Left, Current_chunk) -> - case Continuation() of - stop -> - case Current_chunk of - [] -> - no_more; - - Remaining -> - {last, lists:reverse(Remaining)} - end; - - {continue, E, Next} -> - Chunk = [E | Current_chunk], - case Left > 1 of - false -> - {another, lists:reverse(Chunk), Next}; - - true -> - next_sized_chunk(Next, Left - 1, Chunk) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1043). --spec do_sized_chunk(fun(() -> action(EBJ)), integer()) -> fun(() -> action(list(EBJ))). -do_sized_chunk(Continuation, Count) -> - fun() -> case next_sized_chunk(Continuation, Count, []) of - no_more -> - stop; - - {last, Chunk} -> - {continue, Chunk, fun stop/0}; - - {another, Chunk@1, Next_element} -> - {continue, Chunk@1, do_sized_chunk(Next_element, Count)} - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1080). --spec sized_chunk(iterator(EBN), integer()) -> iterator(list(EBN)). -sized_chunk(Iterator, Count) -> - _pipe = erlang:element(2, Iterator), - _pipe@1 = do_sized_chunk(_pipe, Count), - {iterator, _pipe@1}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1089). --spec do_intersperse(fun(() -> action(EBR)), EBR) -> action(EBR). -do_intersperse(Continuation, Separator) -> - case Continuation() of - stop -> - stop; - - {continue, E, Next} -> - Next_interspersed = fun() -> do_intersperse(Next, Separator) end, - {continue, Separator, fun() -> {continue, E, Next_interspersed} end} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1128). --spec intersperse(iterator(EBU), EBU) -> iterator(EBU). -intersperse(Iterator, Elem) -> - _pipe = fun() -> case (erlang:element(2, Iterator))() of - stop -> - stop; - - {continue, E, Next} -> - {continue, E, fun() -> do_intersperse(Next, Elem) end} - end end, - {iterator, _pipe}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1141). --spec do_any(fun(() -> action(EBX)), fun((EBX) -> boolean())) -> boolean(). -do_any(Continuation, Predicate) -> - case Continuation() of - stop -> - false; - - {continue, E, Next} -> - case Predicate(E) of - true -> - true; - - false -> - do_any(Next, Predicate) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1182). --spec any(iterator(EBZ), fun((EBZ) -> boolean())) -> boolean(). -any(Iterator, Predicate) -> - _pipe = erlang:element(2, Iterator), - do_any(_pipe, Predicate). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1190). --spec do_all(fun(() -> action(ECB)), fun((ECB) -> boolean())) -> boolean(). -do_all(Continuation, Predicate) -> - case Continuation() of - stop -> - true; - - {continue, E, Next} -> - case Predicate(E) of - true -> - do_all(Next, Predicate); - - false -> - false - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1231). --spec all(iterator(ECD), fun((ECD) -> boolean())) -> boolean(). -all(Iterator, Predicate) -> - _pipe = erlang:element(2, Iterator), - do_all(_pipe, Predicate). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1239). --spec update_group_with(ECF) -> fun((gleam@option:option(list(ECF))) -> list(ECF)). -update_group_with(El) -> - fun(Maybe_group) -> case Maybe_group of - {some, Group} -> - [El | Group]; - - none -> - [El] - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1248). --spec group_updater(fun((ECJ) -> ECK)) -> fun((gleam@dict:dict(ECK, list(ECJ)), ECJ) -> gleam@dict:dict(ECK, list(ECJ))). -group_updater(F) -> - fun(Groups, Elem) -> _pipe = Groups, - gleam@dict:upsert(_pipe, F(Elem), update_group_with(Elem)) end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1270). --spec group(iterator(ECR), fun((ECR) -> ECT)) -> gleam@dict:dict(ECT, list(ECR)). -group(Iterator, Key) -> - _pipe = Iterator, - _pipe@1 = fold(_pipe, gleam@dict:new(), group_updater(Key)), - gleam@dict:map_values(_pipe@1, fun(_, Group) -> lists:reverse(Group) end). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1300). --spec reduce(iterator(ECX), fun((ECX, ECX) -> ECX)) -> {ok, ECX} | {error, nil}. -reduce(Iterator, F) -> - case (erlang:element(2, Iterator))() of - stop -> - {error, nil}; - - {continue, E, Next} -> - _pipe = do_fold(Next, F, E), - {ok, _pipe} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1330). --spec last(iterator(EDB)) -> {ok, EDB} | {error, nil}. -last(Iterator) -> - _pipe = Iterator, - reduce(_pipe, fun(_, Elem) -> Elem end). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1344). --spec empty() -> iterator(any()). -empty() -> - {iterator, fun stop/0}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1357). --spec once(fun(() -> EDH)) -> iterator(EDH). -once(F) -> - _pipe = fun() -> {continue, F(), fun stop/0} end, - {iterator, _pipe}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 657). --spec range(integer(), integer()) -> iterator(integer()). -range(Start, Stop) -> - case gleam@int:compare(Start, Stop) of - eq -> - once(fun() -> Start end); - - gt -> - unfold(Start, fun(Current) -> case Current < Stop of - false -> - {next, Current, Current - 1}; - - true -> - done - end end); - - lt -> - unfold(Start, fun(Current@1) -> case Current@1 > Stop of - false -> - {next, Current@1, Current@1 + 1}; - - true -> - done - end end) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1371). --spec single(EDJ) -> iterator(EDJ). -single(Elem) -> - once(fun() -> Elem end). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1375). --spec do_interleave(fun(() -> action(EDL)), fun(() -> action(EDL))) -> action(EDL). -do_interleave(Current, Next) -> - case Current() of - stop -> - Next(); - - {continue, E, Next_other} -> - {continue, E, fun() -> do_interleave(Next, Next_other) end} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1405). --spec interleave(iterator(EDP), iterator(EDP)) -> iterator(EDP). -interleave(Left, Right) -> - _pipe = fun() -> - do_interleave(erlang:element(2, Left), erlang:element(2, Right)) - end, - {iterator, _pipe}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1413). --spec do_fold_until( - fun(() -> action(EDT)), - fun((EDV, EDT) -> gleam@list:continue_or_stop(EDV)), - EDV -) -> EDV. -do_fold_until(Continuation, F, Accumulator) -> - case Continuation() of - stop -> - Accumulator; - - {continue, Elem, Next} -> - case F(Accumulator, Elem) of - {continue, Accumulator@1} -> - do_fold_until(Next, F, Accumulator@1); - - {stop, Accumulator@2} -> - Accumulator@2 - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1452). --spec fold_until( - iterator(EDX), - EDZ, - fun((EDZ, EDX) -> gleam@list:continue_or_stop(EDZ)) -) -> EDZ. -fold_until(Iterator, Initial, F) -> - _pipe = erlang:element(2, Iterator), - do_fold_until(_pipe, F, Initial). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1461). --spec do_try_fold( - fun(() -> action(EEB)), - fun((EED, EEB) -> {ok, EED} | {error, EEE}), - EED -) -> {ok, EED} | {error, EEE}. -do_try_fold(Continuation, F, Accumulator) -> - case Continuation() of - stop -> - {ok, Accumulator}; - - {continue, Elem, Next} -> - case F(Accumulator, Elem) of - {ok, Result} -> - do_try_fold(Next, F, Result); - - {error, _} = Error -> - Error - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1496). --spec try_fold(iterator(EEJ), EEL, fun((EEL, EEJ) -> {ok, EEL} | {error, EEM})) -> {ok, - EEL} | - {error, EEM}. -try_fold(Iterator, Initial, F) -> - _pipe = erlang:element(2, Iterator), - do_try_fold(_pipe, F, Initial). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1519). --spec first(iterator(EER)) -> {ok, EER} | {error, nil}. -first(Iterator) -> - case (erlang:element(2, Iterator))() of - stop -> - {error, nil}; - - {continue, E, _} -> - {ok, E} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1549). --spec at(iterator(EEV), integer()) -> {ok, EEV} | {error, nil}. -at(Iterator, Index) -> - _pipe = Iterator, - _pipe@1 = drop(_pipe, Index), - first(_pipe@1). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1555). --spec do_length(fun(() -> action(any())), integer()) -> integer(). -do_length(Continuation, Length) -> - case Continuation() of - stop -> - Length; - - {continue, _, Next} -> - do_length(Next, Length + 1) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1579). --spec length(iterator(any())) -> integer(). -length(Iterator) -> - _pipe = erlang:element(2, Iterator), - do_length(_pipe, 0). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1601). --spec each(iterator(EFD), fun((EFD) -> any())) -> nil. -each(Iterator, F) -> - _pipe = Iterator, - _pipe@1 = map(_pipe, F), - run(_pipe@1). - --file("/Users/louis/src/gleam/stdlib/src/gleam/iterator.gleam", 1626). --spec yield(EFG, fun(() -> iterator(EFG))) -> iterator(EFG). -yield(Element, Next) -> - {iterator, - fun() -> - {continue, Element, fun() -> (erlang:element(2, Next()))() end} - end}. diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@list.erl b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@list.erl deleted file mode 100644 index fb2164d3f01..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@list.erl +++ /dev/null @@ -1,1442 +0,0 @@ --module(gleam@list). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([length/1, reverse/1, is_empty/1, contains/2, first/1, rest/1, filter/2, filter_map/2, map/2, map2/3, index_map/2, try_map/2, drop/2, take/2, new/0, wrap/1, append/2, prepend/2, concat/1, flatten/1, flat_map/2, fold/3, count/2, group/2, map_fold/3, fold_right/3, index_fold/3, try_fold/3, fold_until/3, find/2, find_map/2, all/2, any/2, zip/2, strict_zip/2, unzip/1, intersperse/2, unique/1, sort/2, range/2, repeat/2, split/2, split_while/2, key_find/2, key_filter/2, pop/2, pop_map/2, key_pop/2, key_set/3, each/2, try_each/2, partition/2, permutations/1, window/2, window_by_2/1, drop_while/2, take_while/2, chunk/2, sized_chunk/2, reduce/2, scan/3, last/1, combinations/2, combination_pairs/1, transpose/1, interleave/1, shuffle/1]). --export_type([continue_or_stop/1, sorting/0]). - --type continue_or_stop(AAO) :: {continue, AAO} | {stop, AAO}. - --type sorting() :: ascending | descending. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 61). --spec count_length(list(any()), integer()) -> integer(). -count_length(List, Count) -> - case List of - [_ | List@1] -> - count_length(List@1, Count + 1); - - _ -> - Count - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 57). --spec length(list(any())) -> integer(). -length(List) -> - erlang:length(List). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 130). --spec do_reverse(list(AAY), list(AAY)) -> list(AAY). -do_reverse(Remaining, Accumulator) -> - case Remaining of - [] -> - Accumulator; - - [Item | Rest] -> - do_reverse(Rest, [Item | Accumulator]) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 126). --spec reverse(list(AAV)) -> list(AAV). -reverse(List) -> - lists:reverse(List). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 158). --spec is_empty(list(any())) -> boolean(). -is_empty(List) -> - List =:= []. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 194). --spec contains(list(ABE), ABE) -> boolean(). -contains(List, Elem) -> - case List of - [] -> - false; - - [First | _] when First =:= Elem -> - true; - - [_ | Rest] -> - contains(Rest, Elem) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 221). --spec first(list(ABG)) -> {ok, ABG} | {error, nil}. -first(List) -> - case List of - [] -> - {error, nil}; - - [X | _] -> - {ok, X} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 250). --spec rest(list(ABK)) -> {ok, list(ABK)} | {error, nil}. -rest(List) -> - case List of - [] -> - {error, nil}; - - [_ | Rest] -> - {ok, Rest} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 257). --spec update_group(fun((ABP) -> ABQ)) -> fun((gleam@dict:dict(ABQ, list(ABP)), ABP) -> gleam@dict:dict(ABQ, list(ABP))). -update_group(F) -> - fun(Groups, Elem) -> case gleam@dict:get(Groups, F(Elem)) of - {ok, Existing} -> - gleam@dict:insert(Groups, F(Elem), [Elem | Existing]); - - {error, _} -> - gleam@dict:insert(Groups, F(Elem), [Elem]) - end end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 302). --spec do_filter(list(ACD), fun((ACD) -> boolean()), list(ACD)) -> list(ACD). -do_filter(List, Fun, Acc) -> - case List of - [] -> - lists:reverse(Acc); - - [First | Rest] -> - New_acc = case Fun(First) of - true -> - [First | Acc]; - - false -> - Acc - end, - do_filter(Rest, Fun, New_acc) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 330). --spec filter(list(ACH), fun((ACH) -> boolean())) -> list(ACH). -filter(List, Predicate) -> - do_filter(List, Predicate, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 334). --spec do_filter_map( - list(ACK), - fun((ACK) -> {ok, ACM} | {error, any()}), - list(ACM) -) -> list(ACM). -do_filter_map(List, Fun, Acc) -> - case List of - [] -> - lists:reverse(Acc); - - [First | Rest] -> - New_acc = case Fun(First) of - {ok, First@1} -> - [First@1 | Acc]; - - {error, _} -> - Acc - end, - do_filter_map(Rest, Fun, New_acc) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 366). --spec filter_map(list(ACS), fun((ACS) -> {ok, ACU} | {error, any()})) -> list(ACU). -filter_map(List, Fun) -> - do_filter_map(List, Fun, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 370). --spec do_map(list(ACZ), fun((ACZ) -> ADB), list(ADB)) -> list(ADB). -do_map(List, Fun, Acc) -> - case List of - [] -> - lists:reverse(Acc); - - [First | Rest] -> - do_map(Rest, Fun, [Fun(First) | Acc]) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 387). --spec map(list(ADE), fun((ADE) -> ADG)) -> list(ADG). -map(List, Fun) -> - do_map(List, Fun, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 411). --spec do_map2(list(ADO), list(ADQ), fun((ADO, ADQ) -> ADS), list(ADS)) -> list(ADS). -do_map2(List1, List2, Fun, Acc) -> - case {List1, List2} of - {[], _} -> - lists:reverse(Acc); - - {_, []} -> - lists:reverse(Acc); - - {[A | As_], [B | Bs]} -> - do_map2(As_, Bs, Fun, [Fun(A, B) | Acc]) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 407). --spec map2(list(ADI), list(ADK), fun((ADI, ADK) -> ADM)) -> list(ADM). -map2(List1, List2, Fun) -> - do_map2(List1, List2, Fun, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 449). --spec do_index_map( - list(AEA), - fun((AEA, integer()) -> AEC), - integer(), - list(AEC) -) -> list(AEC). -do_index_map(List, Fun, Index, Acc) -> - case List of - [] -> - lists:reverse(Acc); - - [First | Rest] -> - Acc@1 = [Fun(First, Index) | Acc], - do_index_map(Rest, Fun, Index + 1, Acc@1) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 477). --spec index_map(list(AEF), fun((AEF, integer()) -> AEH)) -> list(AEH). -index_map(List, Fun) -> - do_index_map(List, Fun, 0, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 481). --spec do_try_map(list(AEJ), fun((AEJ) -> {ok, AEL} | {error, AEM}), list(AEL)) -> {ok, - list(AEL)} | - {error, AEM}. -do_try_map(List, Fun, Acc) -> - case List of - [] -> - {ok, lists:reverse(Acc)}; - - [First | Rest] -> - case Fun(First) of - {ok, First@1} -> - do_try_map(Rest, Fun, [First@1 | Acc]); - - {error, Error} -> - {error, Error} - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 528). --spec try_map(list(AET), fun((AET) -> {ok, AEV} | {error, AEW})) -> {ok, - list(AEV)} | - {error, AEW}. -try_map(List, Fun) -> - do_try_map(List, Fun, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 555). --spec drop(list(AFC), integer()) -> list(AFC). -drop(List, N) -> - case N =< 0 of - true -> - List; - - false -> - case List of - [] -> - []; - - [_ | Rest] -> - drop(Rest, N - 1) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 566). --spec do_take(list(AFF), integer(), list(AFF)) -> list(AFF). -do_take(List, N, Acc) -> - case N =< 0 of - true -> - lists:reverse(Acc); - - false -> - case List of - [] -> - lists:reverse(Acc); - - [First | Rest] -> - do_take(Rest, N - 1, [First | Acc]) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 597). --spec take(list(AFJ), integer()) -> list(AFJ). -take(List, N) -> - do_take(List, N, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 610). --spec new() -> list(any()). -new() -> - []. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 630). --spec wrap(AFO) -> list(AFO). -wrap(Item) -> - [Item]. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 651). --spec do_append(list(AFU), list(AFU)) -> list(AFU). -do_append(First, Second) -> - case First of - [] -> - Second; - - [Item | Rest] -> - do_append(Rest, [Item | Second]) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 647). --spec append(list(AFQ), list(AFQ)) -> list(AFQ). -append(First, Second) -> - lists:append(First, Second). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 671). --spec prepend(list(AFY), AFY) -> list(AFY). -prepend(List, Item) -> - [Item | List]. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 676). --spec reverse_and_prepend(list(AGB), list(AGB)) -> list(AGB). -reverse_and_prepend(Prefix, Suffix) -> - case Prefix of - [] -> - Suffix; - - [First | Rest] -> - reverse_and_prepend(Rest, [First | Suffix]) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 683). --spec do_concat(list(list(AGF)), list(AGF)) -> list(AGF). -do_concat(Lists, Acc) -> - case Lists of - [] -> - lists:reverse(Acc); - - [List | Further_lists] -> - do_concat(Further_lists, reverse_and_prepend(List, Acc)) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 703). --spec concat(list(list(AGK))) -> list(AGK). -concat(Lists) -> - do_concat(Lists, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 719). --spec flatten(list(list(AGO))) -> list(AGO). -flatten(Lists) -> - do_concat(Lists, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 732). --spec flat_map(list(AGS), fun((AGS) -> list(AGU))) -> list(AGU). -flat_map(List, Fun) -> - _pipe = map(List, Fun), - flatten(_pipe). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 745). --spec fold(list(AGX), AGZ, fun((AGZ, AGX) -> AGZ)) -> AGZ. -fold(List, Initial, Fun) -> - case List of - [] -> - Initial; - - [X | Rest] -> - fold(Rest, Fun(Initial, X), Fun) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 90). --spec count(list(AAT), fun((AAT) -> boolean())) -> integer(). -count(List, Predicate) -> - fold(List, 0, fun(Acc, Value) -> case Predicate(Value) of - true -> - Acc + 1; - - false -> - Acc - end end). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 298). --spec group(list(ABX), fun((ABX) -> ABZ)) -> gleam@dict:dict(ABZ, list(ABX)). -group(List, Key) -> - fold(List, gleam@dict:new(), update_group(Key)). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 436). --spec map_fold(list(ADV), ADX, fun((ADX, ADV) -> {ADX, ADY})) -> {ADX, - list(ADY)}. -map_fold(List, Initial, Fun) -> - _pipe = fold( - List, - {Initial, []}, - fun(Acc, Item) -> - {Current_acc, Items} = Acc, - {Next_acc, Next_item} = Fun(Current_acc, Item), - {Next_acc, [Next_item | Items]} - end - ), - gleam@pair:map_second(_pipe, fun lists:reverse/1). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 767). --spec fold_right(list(AHA), AHC, fun((AHC, AHA) -> AHC)) -> AHC. -fold_right(List, Initial, Fun) -> - case List of - [] -> - Initial; - - [X | Rest] -> - Fun(fold_right(Rest, Initial, Fun), X) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 778). --spec do_index_fold( - list(AHD), - AHF, - fun((AHF, AHD, integer()) -> AHF), - integer() -) -> AHF. -do_index_fold(Over, Acc, With, Index) -> - case Over of - [] -> - Acc; - - [First | Rest] -> - do_index_fold(Rest, With(Acc, First, Index), With, Index + 1) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 800). --spec index_fold(list(AHG), AHI, fun((AHI, AHG, integer()) -> AHI)) -> AHI. -index_fold(List, Initial, Fun) -> - do_index_fold(List, Initial, Fun, 0). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 827). --spec try_fold(list(AHJ), AHL, fun((AHL, AHJ) -> {ok, AHL} | {error, AHM})) -> {ok, - AHL} | - {error, AHM}. -try_fold(List, Initial, Fun) -> - case List of - [] -> - {ok, Initial}; - - [First | Rest] -> - case Fun(Initial, First) of - {ok, Result} -> - try_fold(Rest, Result, Fun); - - {error, _} = Error -> - Error - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 866). --spec fold_until(list(AHR), AHT, fun((AHT, AHR) -> continue_or_stop(AHT))) -> AHT. -fold_until(List, Initial, Fun) -> - case List of - [] -> - Initial; - - [First | Rest] -> - case Fun(Initial, First) of - {continue, Next_accumulator} -> - fold_until(Rest, Next_accumulator, Fun); - - {stop, B} -> - B - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 903). --spec find(list(AHV), fun((AHV) -> boolean())) -> {ok, AHV} | {error, nil}. -find(List, Is_desired) -> - case List of - [] -> - {error, nil}; - - [X | Rest] -> - case Is_desired(X) of - true -> - {ok, X}; - - _ -> - find(Rest, Is_desired) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 939). --spec find_map(list(AHZ), fun((AHZ) -> {ok, AIB} | {error, any()})) -> {ok, AIB} | - {error, nil}. -find_map(List, Fun) -> - case List of - [] -> - {error, nil}; - - [X | Rest] -> - case Fun(X) of - {ok, X@1} -> - {ok, X@1}; - - _ -> - find_map(Rest, Fun) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 974). --spec all(list(AIH), fun((AIH) -> boolean())) -> boolean(). -all(List, Predicate) -> - case List of - [] -> - true; - - [First | Rest] -> - case Predicate(First) of - true -> - all(Rest, Predicate); - - false -> - false - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1011). --spec any(list(AIJ), fun((AIJ) -> boolean())) -> boolean(). -any(List, Predicate) -> - case List of - [] -> - false; - - [First | Rest] -> - case Predicate(First) of - true -> - true; - - false -> - any(Rest, Predicate) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1022). --spec do_zip(list(AIL), list(AIN), list({AIL, AIN})) -> list({AIL, AIN}). -do_zip(One, Other, Acc) -> - case {One, Other} of - {[First_one | Rest_one], [First_other | Rest_other]} -> - do_zip(Rest_one, Rest_other, [{First_one, First_other} | Acc]); - - {_, _} -> - lists:reverse(Acc) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1057). --spec zip(list(AIR), list(AIT)) -> list({AIR, AIT}). -zip(List, Other) -> - do_zip(List, Other, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1087). --spec strict_zip(list(AIW), list(AIY)) -> {ok, list({AIW, AIY})} | {error, nil}. -strict_zip(List, Other) -> - case erlang:length(List) =:= erlang:length(Other) of - true -> - {ok, zip(List, Other)}; - - false -> - {error, nil} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1097). --spec do_unzip(list({AJD, AJE}), list(AJD), list(AJE)) -> {list(AJD), list(AJE)}. -do_unzip(Input, One, Other) -> - case Input of - [] -> - {lists:reverse(One), lists:reverse(Other)}; - - [{First_one, First_other} | Rest] -> - do_unzip(Rest, [First_one | One], [First_other | Other]) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1123). --spec unzip(list({AJK, AJL})) -> {list(AJK), list(AJL)}. -unzip(Input) -> - do_unzip(Input, [], []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1127). --spec do_intersperse(list(AJP), AJP, list(AJP)) -> list(AJP). -do_intersperse(List, Separator, Acc) -> - case List of - [] -> - lists:reverse(Acc); - - [X | Rest] -> - do_intersperse(Rest, Separator, [X, Separator | Acc]) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1150). --spec intersperse(list(AJT), AJT) -> list(AJT). -intersperse(List, Elem) -> - case List of - [] -> - List; - - [_] -> - List; - - [X | Rest] -> - do_intersperse(Rest, Elem, [X]) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1168). --spec unique(list(AJW)) -> list(AJW). -unique(List) -> - case List of - [] -> - []; - - [X | Rest] -> - [X | unique(filter(Rest, fun(Y) -> Y /= X end))] - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1249). --spec sequences( - list(AKC), - fun((AKC, AKC) -> gleam@order:order()), - list(AKC), - sorting(), - AKC, - list(list(AKC)) -) -> list(list(AKC)). -sequences(List, Compare, Growing, Direction, Prev, Acc) -> - Growing@1 = [Prev | Growing], - case List of - [] -> - case Direction of - ascending -> - [do_reverse(Growing@1, []) | Acc]; - - descending -> - [Growing@1 | Acc] - end; - - [New | Rest] -> - case {Compare(Prev, New), Direction} of - {gt, descending} -> - sequences(Rest, Compare, Growing@1, Direction, New, Acc); - - {lt, ascending} -> - sequences(Rest, Compare, Growing@1, Direction, New, Acc); - - {eq, ascending} -> - sequences(Rest, Compare, Growing@1, Direction, New, Acc); - - {gt, ascending} -> - Acc@1 = case Direction of - ascending -> - [do_reverse(Growing@1, []) | Acc]; - - descending -> - [Growing@1 | Acc] - end, - case Rest of - [] -> - [[New] | Acc@1]; - - [Next | Rest@1] -> - Direction@1 = case Compare(New, Next) of - lt -> - ascending; - - eq -> - ascending; - - gt -> - descending - end, - sequences( - Rest@1, - Compare, - [New], - Direction@1, - Next, - Acc@1 - ) - end; - - {lt, descending} -> - Acc@1 = case Direction of - ascending -> - [do_reverse(Growing@1, []) | Acc]; - - descending -> - [Growing@1 | Acc] - end, - case Rest of - [] -> - [[New] | Acc@1]; - - [Next | Rest@1] -> - Direction@1 = case Compare(New, Next) of - lt -> - ascending; - - eq -> - ascending; - - gt -> - descending - end, - sequences( - Rest@1, - Compare, - [New], - Direction@1, - Next, - Acc@1 - ) - end; - - {eq, descending} -> - Acc@1 = case Direction of - ascending -> - [do_reverse(Growing@1, []) | Acc]; - - descending -> - [Growing@1 | Acc] - end, - case Rest of - [] -> - [[New] | Acc@1]; - - [Next | Rest@1] -> - Direction@1 = case Compare(New, Next) of - lt -> - ascending; - - eq -> - ascending; - - gt -> - descending - end, - sequences( - Rest@1, - Compare, - [New], - Direction@1, - Next, - Acc@1 - ) - end - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1397). --spec merge_ascendings( - list(AKZ), - list(AKZ), - fun((AKZ, AKZ) -> gleam@order:order()), - list(AKZ) -) -> list(AKZ). -merge_ascendings(List1, List2, Compare, Acc) -> - case {List1, List2} of - {[], List} -> - do_reverse(List, Acc); - - {List, []} -> - do_reverse(List, Acc); - - {[First1 | Rest1], [First2 | Rest2]} -> - case Compare(First1, First2) of - lt -> - merge_ascendings(Rest1, List2, Compare, [First1 | Acc]); - - gt -> - merge_ascendings(List1, Rest2, Compare, [First2 | Acc]); - - eq -> - merge_ascendings(List1, Rest2, Compare, [First2 | Acc]) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1350). --spec merge_ascending_pairs( - list(list(AKN)), - fun((AKN, AKN) -> gleam@order:order()), - list(list(AKN)) -) -> list(list(AKN)). -merge_ascending_pairs(Sequences, Compare, Acc) -> - case Sequences of - [] -> - do_reverse(Acc, []); - - [Sequence] -> - do_reverse([do_reverse(Sequence, []) | Acc], []); - - [Ascending1, Ascending2 | Rest] -> - Descending = merge_ascendings(Ascending1, Ascending2, Compare, []), - merge_ascending_pairs(Rest, Compare, [Descending | Acc]) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1424). --spec merge_descendings( - list(ALE), - list(ALE), - fun((ALE, ALE) -> gleam@order:order()), - list(ALE) -) -> list(ALE). -merge_descendings(List1, List2, Compare, Acc) -> - case {List1, List2} of - {[], List} -> - do_reverse(List, Acc); - - {List, []} -> - do_reverse(List, Acc); - - {[First1 | Rest1], [First2 | Rest2]} -> - case Compare(First1, First2) of - lt -> - merge_descendings(List1, Rest2, Compare, [First2 | Acc]); - - gt -> - merge_descendings(Rest1, List2, Compare, [First1 | Acc]); - - eq -> - merge_descendings(Rest1, List2, Compare, [First1 | Acc]) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1372). --spec merge_descending_pairs( - list(list(AKT)), - fun((AKT, AKT) -> gleam@order:order()), - list(list(AKT)) -) -> list(list(AKT)). -merge_descending_pairs(Sequences, Compare, Acc) -> - case Sequences of - [] -> - do_reverse(Acc, []); - - [Sequence] -> - do_reverse([do_reverse(Sequence, []) | Acc], []); - - [Descending1, Descending2 | Rest] -> - Ascending = merge_descendings(Descending1, Descending2, Compare, []), - merge_descending_pairs(Rest, Compare, [Ascending | Acc]) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1316). --spec merge_all( - list(list(AKJ)), - sorting(), - fun((AKJ, AKJ) -> gleam@order:order()) -) -> list(AKJ). -merge_all(Sequences, Direction, Compare) -> - case {Sequences, Direction} of - {[], _} -> - []; - - {[Sequence], ascending} -> - Sequence; - - {[Sequence@1], descending} -> - do_reverse(Sequence@1, []); - - {_, ascending} -> - Sequences@1 = merge_ascending_pairs(Sequences, Compare, []), - merge_all(Sequences@1, descending, Compare); - - {_, descending} -> - Sequences@2 = merge_descending_pairs(Sequences, Compare, []), - merge_all(Sequences@2, ascending, Compare) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1187). --spec sort(list(AJZ), fun((AJZ, AJZ) -> gleam@order:order())) -> list(AJZ). -sort(List, Compare) -> - case List of - [] -> - []; - - [X] -> - [X]; - - [X@1, Y | Rest] -> - Direction = case Compare(X@1, Y) of - lt -> - ascending; - - eq -> - ascending; - - gt -> - descending - end, - Sequences = sequences(Rest, Compare, [X@1], Direction, Y, []), - merge_all(Sequences, ascending, Compare) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1464). --spec tail_recursive_range(integer(), integer(), list(integer())) -> list(integer()). -tail_recursive_range(Start, Stop, Acc) -> - case gleam@int:compare(Start, Stop) of - eq -> - [Stop | Acc]; - - gt -> - tail_recursive_range(Start, Stop + 1, [Stop | Acc]); - - lt -> - tail_recursive_range(Start, Stop - 1, [Stop | Acc]) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1460). --spec range(integer(), integer()) -> list(integer()). -range(Start, Stop) -> - tail_recursive_range(Start, Stop, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1472). --spec do_repeat(ALM, integer(), list(ALM)) -> list(ALM). -do_repeat(Item, Times, Acc) -> - case Times =< 0 of - true -> - Acc; - - false -> - do_repeat(Item, Times - 1, [Item | Acc]) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1493). --spec repeat(ALP, integer()) -> list(ALP). -repeat(A, Times) -> - do_repeat(A, Times, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1497). --spec do_split(list(ALR), integer(), list(ALR)) -> {list(ALR), list(ALR)}. -do_split(List, N, Taken) -> - case N =< 0 of - true -> - {lists:reverse(Taken), List}; - - false -> - case List of - [] -> - {lists:reverse(Taken), []}; - - [First | Rest] -> - do_split(Rest, N - 1, [First | Taken]) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1530). --spec split(list(ALW), integer()) -> {list(ALW), list(ALW)}. -split(List, Index) -> - do_split(List, Index, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1534). --spec do_split_while(list(AMA), fun((AMA) -> boolean()), list(AMA)) -> {list(AMA), - list(AMA)}. -do_split_while(List, F, Acc) -> - case List of - [] -> - {lists:reverse(Acc), []}; - - [First | Rest] -> - case F(First) of - false -> - {lists:reverse(Acc), List}; - - _ -> - do_split_while(Rest, F, [First | Acc]) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1567). --spec split_while(list(AMF), fun((AMF) -> boolean())) -> {list(AMF), list(AMF)}. -split_while(List, Predicate) -> - do_split_while(List, Predicate, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1599). --spec key_find(list({AMJ, AMK}), AMJ) -> {ok, AMK} | {error, nil}. -key_find(Keyword_list, Desired_key) -> - find_map( - Keyword_list, - fun(Keyword) -> - {Key, Value} = Keyword, - case Key =:= Desired_key of - true -> - {ok, Value}; - - false -> - {error, nil} - end - end - ). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1630). --spec key_filter(list({AMO, AMP}), AMO) -> list(AMP). -key_filter(Keyword_list, Desired_key) -> - filter_map( - Keyword_list, - fun(Keyword) -> - {Key, Value} = Keyword, - case Key =:= Desired_key of - true -> - {ok, Value}; - - false -> - {error, nil} - end - end - ). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1643). --spec do_pop(list(BEX), fun((BEX) -> boolean()), list(BEX)) -> {ok, - {BEX, list(BEX)}} | - {error, nil}. -do_pop(Haystack, Predicate, Checked) -> - case Haystack of - [] -> - {error, nil}; - - [X | Rest] -> - case Predicate(X) of - true -> - {ok, {X, lists:append(lists:reverse(Checked), Rest)}}; - - false -> - do_pop(Rest, Predicate, [X | Checked]) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1675). --spec pop(list(AMW), fun((AMW) -> boolean())) -> {ok, {AMW, list(AMW)}} | - {error, nil}. -pop(List, Is_desired) -> - do_pop(List, Is_desired, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1682). --spec do_pop_map(list(ANB), fun((ANB) -> {ok, AND} | {error, any()}), list(ANB)) -> {ok, - {AND, list(ANB)}} | - {error, nil}. -do_pop_map(List, Mapper, Checked) -> - case List of - [] -> - {error, nil}; - - [X | Rest] -> - case Mapper(X) of - {ok, Y} -> - {ok, {Y, lists:append(lists:reverse(Checked), Rest)}}; - - {error, _} -> - do_pop_map(Rest, Mapper, [X | Checked]) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1719). --spec pop_map(list(ANL), fun((ANL) -> {ok, ANN} | {error, any()})) -> {ok, - {ANN, list(ANL)}} | - {error, nil}. -pop_map(Haystack, Is_desired) -> - do_pop_map(Haystack, Is_desired, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1749). --spec key_pop(list({ANU, ANV}), ANU) -> {ok, {ANV, list({ANU, ANV})}} | - {error, nil}. -key_pop(List, Key) -> - pop_map( - List, - fun(Entry) -> - {K, V} = Entry, - case K of - K@1 when K@1 =:= Key -> - {ok, V}; - - _ -> - {error, nil} - end - end - ). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1776). --spec key_set(list({AOA, AOB}), AOA, AOB) -> list({AOA, AOB}). -key_set(List, Key, Value) -> - case List of - [] -> - [{Key, Value}]; - - [{K, _} | Rest] when K =:= Key -> - [{Key, Value} | Rest]; - - [First | Rest@1] -> - [First | key_set(Rest@1, Key, Value)] - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1798). --spec each(list(AOE), fun((AOE) -> any())) -> nil. -each(List, F) -> - case List of - [] -> - nil; - - [First | Rest] -> - F(First), - each(Rest, F) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1824). --spec try_each(list(AOH), fun((AOH) -> {ok, any()} | {error, AOK})) -> {ok, nil} | - {error, AOK}. -try_each(List, Fun) -> - case List of - [] -> - {ok, nil}; - - [First | Rest] -> - case Fun(First) of - {ok, _} -> - try_each(Rest, Fun); - - {error, E} -> - {error, E} - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1838). --spec do_partition(list(BHC), fun((BHC) -> boolean()), list(BHC), list(BHC)) -> {list(BHC), - list(BHC)}. -do_partition(List, Categorise, Trues, Falses) -> - case List of - [] -> - {lists:reverse(Trues), lists:reverse(Falses)}; - - [First | Rest] -> - case Categorise(First) of - true -> - do_partition(Rest, Categorise, [First | Trues], Falses); - - false -> - do_partition(Rest, Categorise, Trues, [First | Falses]) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1861). --spec partition(list(AOU), fun((AOU) -> boolean())) -> {list(AOU), list(AOU)}. -partition(List, Categorise) -> - do_partition(List, Categorise, [], []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1877). --spec permutations(list(AOY)) -> list(list(AOY)). -permutations(List) -> - case List of - [] -> - [[]]; - - _ -> - _pipe@3 = index_map( - List, - fun(I, I_idx) -> - _pipe = index_fold( - List, - [], - fun(Acc, J, J_idx) -> case I_idx =:= J_idx of - true -> - Acc; - - false -> - [J | Acc] - end end - ), - _pipe@1 = lists:reverse(_pipe), - _pipe@2 = permutations(_pipe@1), - map(_pipe@2, fun(Permutation) -> [I | Permutation] end) - end - ), - flatten(_pipe@3) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1896). --spec do_window(list(list(APC)), list(APC), integer()) -> list(list(APC)). -do_window(Acc, List, N) -> - Window = take(List, N), - case erlang:length(Window) =:= N of - true -> - do_window([Window | Acc], drop(List, 1), N); - - false -> - Acc - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1919). --spec window(list(API), integer()) -> list(list(API)). -window(List, N) -> - case N =< 0 of - true -> - []; - - false -> - _pipe = do_window([], List, N), - lists:reverse(_pipe) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1940). --spec window_by_2(list(APM)) -> list({APM, APM}). -window_by_2(List) -> - zip(List, drop(List, 1)). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1953). --spec drop_while(list(APP), fun((APP) -> boolean())) -> list(APP). -drop_while(List, Predicate) -> - case List of - [] -> - []; - - [First | Rest] -> - case Predicate(First) of - true -> - drop_while(Rest, Predicate); - - false -> - [First | Rest] - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1967). --spec do_take_while(list(APS), fun((APS) -> boolean()), list(APS)) -> list(APS). -do_take_while(List, Predicate, Acc) -> - case List of - [] -> - lists:reverse(Acc); - - [First | Rest] -> - case Predicate(First) of - true -> - do_take_while(Rest, Predicate, [First | Acc]); - - false -> - lists:reverse(Acc) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1991). --spec take_while(list(APW), fun((APW) -> boolean())) -> list(APW). -take_while(List, Predicate) -> - do_take_while(List, Predicate, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 1998). --spec do_chunk(list(APZ), fun((APZ) -> AQB), AQB, list(APZ), list(list(APZ))) -> list(list(APZ)). -do_chunk(List, F, Previous_key, Current_chunk, Acc) -> - case List of - [First | Rest] -> - Key = F(First), - case Key =:= Previous_key of - false -> - New_acc = [lists:reverse(Current_chunk) | Acc], - do_chunk(Rest, F, Key, [First], New_acc); - - _ -> - do_chunk(Rest, F, Key, [First | Current_chunk], Acc) - end; - - _ -> - lists:reverse([lists:reverse(Current_chunk) | Acc]) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 2030). --spec chunk(list(AQH), fun((AQH) -> any())) -> list(list(AQH)). -chunk(List, F) -> - case List of - [] -> - []; - - [First | Rest] -> - do_chunk(Rest, F, F(First), [First], []) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 2037). --spec do_sized_chunk( - list(AQM), - integer(), - integer(), - list(AQM), - list(list(AQM)) -) -> list(list(AQM)). -do_sized_chunk(List, Count, Left, Current_chunk, Acc) -> - case List of - [] -> - case Current_chunk of - [] -> - lists:reverse(Acc); - - Remaining -> - lists:reverse([lists:reverse(Remaining) | Acc]) - end; - - [First | Rest] -> - Chunk = [First | Current_chunk], - case Left > 1 of - false -> - do_sized_chunk( - Rest, - Count, - Count, - [], - [lists:reverse(Chunk) | Acc] - ); - - true -> - do_sized_chunk(Rest, Count, Left - 1, Chunk, Acc) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 2079). --spec sized_chunk(list(AQT), integer()) -> list(list(AQT)). -sized_chunk(List, Count) -> - do_sized_chunk(List, Count, Count, [], []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 2103). --spec reduce(list(AQX), fun((AQX, AQX) -> AQX)) -> {ok, AQX} | {error, nil}. -reduce(List, Fun) -> - case List of - [] -> - {error, nil}; - - [First | Rest] -> - {ok, fold(Rest, First, Fun)} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 2110). --spec do_scan(list(ARB), ARD, list(ARD), fun((ARD, ARB) -> ARD)) -> list(ARD). -do_scan(List, Accumulator, Accumulated, Fun) -> - case List of - [] -> - lists:reverse(Accumulated); - - [First | Rest] -> - Next = Fun(Accumulator, First), - do_scan(Rest, Next, [Next | Accumulated], Fun) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 2134). --spec scan(list(ARG), ARI, fun((ARI, ARG) -> ARI)) -> list(ARI). -scan(List, Initial, Fun) -> - do_scan(List, Initial, [], Fun). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 2162). --spec last(list(ARK)) -> {ok, ARK} | {error, nil}. -last(List) -> - _pipe = List, - reduce(_pipe, fun(_, Elem) -> Elem end). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 2181). --spec combinations(list(ARO), integer()) -> list(list(ARO)). -combinations(Items, N) -> - case N of - 0 -> - [[]]; - - _ -> - case Items of - [] -> - []; - - [First | Rest] -> - First_combinations = begin - _pipe = map( - combinations(Rest, N - 1), - fun(Com) -> [First | Com] end - ), - lists:reverse(_pipe) - end, - fold( - First_combinations, - combinations(Rest, N), - fun(Acc, C) -> [C | Acc] end - ) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 2199). --spec do_combination_pairs(list(ARS)) -> list(list({ARS, ARS})). -do_combination_pairs(Items) -> - case Items of - [] -> - []; - - [First | Rest] -> - First_combinations = map(Rest, fun(Other) -> {First, Other} end), - [First_combinations | do_combination_pairs(Rest)] - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 2218). --spec combination_pairs(list(ARW)) -> list({ARW, ARW}). -combination_pairs(Items) -> - _pipe = do_combination_pairs(Items), - flatten(_pipe). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 2250). --spec transpose(list(list(ASD))) -> list(list(ASD)). -transpose(List_of_list) -> - Take_first = fun(List) -> case List of - [] -> - []; - - [F] -> - [F]; - - [F@1 | _] -> - [F@1] - end end, - case List_of_list of - [] -> - []; - - [[] | Rest] -> - transpose(Rest); - - Rows -> - Firsts = begin - _pipe = Rows, - _pipe@1 = map(_pipe, Take_first), - flatten(_pipe@1) - end, - Rest@1 = transpose( - map(Rows, fun(_capture) -> drop(_capture, 1) end) - ), - [Firsts | Rest@1] - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 2232). --spec interleave(list(list(ARZ))) -> list(ARZ). -interleave(List) -> - _pipe = transpose(List), - flatten(_pipe). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 2273). --spec do_shuffle_pair_unwrap(list({float(), ASI}), list(ASI)) -> list(ASI). -do_shuffle_pair_unwrap(List, Acc) -> - case List of - [] -> - Acc; - - [Elem_pair | Enumerable] -> - do_shuffle_pair_unwrap( - Enumerable, - [erlang:element(2, Elem_pair) | Acc] - ) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 2281). --spec do_shuffle_by_pair_indexes(list({float(), ASM})) -> list({float(), ASM}). -do_shuffle_by_pair_indexes(List_of_pairs) -> - sort( - List_of_pairs, - fun(A_pair, B_pair) -> - gleam@float:compare( - erlang:element(1, A_pair), - erlang:element(1, B_pair) - ) - end - ). - --file("/Users/louis/src/gleam/stdlib/src/gleam/list.gleam", 2300). --spec shuffle(list(ASP)) -> list(ASP). -shuffle(List) -> - _pipe = List, - _pipe@1 = fold(_pipe, [], fun(Acc, A) -> [{rand:uniform(), A} | Acc] end), - _pipe@2 = do_shuffle_by_pair_indexes(_pipe@1), - do_shuffle_pair_unwrap(_pipe@2, []). diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@option.erl b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@option.erl deleted file mode 100644 index 9348cc1ec6b..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@option.erl +++ /dev/null @@ -1,162 +0,0 @@ --module(gleam@option). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([all/1, is_some/1, is_none/1, to_result/2, from_result/1, unwrap/2, lazy_unwrap/2, map/2, flatten/1, then/2, 'or'/2, lazy_or/2, values/1]). --export_type([option/1]). - --type option(FV) :: {some, FV} | none. - --file("/Users/louis/src/gleam/stdlib/src/gleam/option.gleam", 24). --spec do_all(list(option(FW)), list(FW)) -> option(list(FW)). -do_all(List, Acc) -> - case List of - [] -> - {some, Acc}; - - [X | Rest] -> - Accumulate = fun(Acc@1, Item) -> case {Acc@1, Item} of - {{some, Values}, {some, Value}} -> - {some, [Value | Values]}; - - {_, _} -> - none - end end, - Accumulate(do_all(Rest, Acc), X) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/option.gleam", 55). --spec all(list(option(GC))) -> option(list(GC)). -all(List) -> - do_all(List, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/option.gleam", 73). --spec is_some(option(any())) -> boolean(). -is_some(Option) -> - Option /= none. - --file("/Users/louis/src/gleam/stdlib/src/gleam/option.gleam", 91). --spec is_none(option(any())) -> boolean(). -is_none(Option) -> - Option =:= none. - --file("/Users/louis/src/gleam/stdlib/src/gleam/option.gleam", 109). --spec to_result(option(GL), GO) -> {ok, GL} | {error, GO}. -to_result(Option, E) -> - case Option of - {some, A} -> - {ok, A}; - - _ -> - {error, E} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/option.gleam", 130). --spec from_result({ok, GR} | {error, any()}) -> option(GR). -from_result(Result) -> - case Result of - {ok, A} -> - {some, A}; - - _ -> - none - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/option.gleam", 151). --spec unwrap(option(GW), GW) -> GW. -unwrap(Option, Default) -> - case Option of - {some, X} -> - X; - - none -> - Default - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/option.gleam", 172). --spec lazy_unwrap(option(GY), fun(() -> GY)) -> GY. -lazy_unwrap(Option, Default) -> - case Option of - {some, X} -> - X; - - none -> - Default() - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/option.gleam", 197). --spec map(option(HA), fun((HA) -> HC)) -> option(HC). -map(Option, Fun) -> - case Option of - {some, X} -> - {some, Fun(X)}; - - none -> - none - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/option.gleam", 223). --spec flatten(option(option(HE))) -> option(HE). -flatten(Option) -> - case Option of - {some, X} -> - X; - - none -> - none - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/option.gleam", 262). --spec then(option(HI), fun((HI) -> option(HK))) -> option(HK). -then(Option, Fun) -> - case Option of - {some, X} -> - Fun(X); - - none -> - none - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/option.gleam", 293). --spec 'or'(option(HN), option(HN)) -> option(HN). -'or'(First, Second) -> - case First of - {some, _} -> - First; - - none -> - Second - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/option.gleam", 324). --spec lazy_or(option(HR), fun(() -> option(HR))) -> option(HR). -lazy_or(First, Second) -> - case First of - {some, _} -> - First; - - none -> - Second() - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/option.gleam", 331). --spec do_values(list(option(HV)), list(HV)) -> list(HV). -do_values(List, Acc) -> - case List of - [] -> - Acc; - - [First | Rest] -> - Accumulate = fun(Acc@1, Item) -> case Item of - {some, Value} -> - [Value | Acc@1]; - - none -> - Acc@1 - end end, - Accumulate(do_values(Rest, Acc), First) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/option.gleam", 356). --spec values(list(option(IA))) -> list(IA). -values(Options) -> - do_values(Options, []). diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@order.erl b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@order.erl deleted file mode 100644 index 415ecc11fa8..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@order.erl +++ /dev/null @@ -1,85 +0,0 @@ --module(gleam@order). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([negate/1, to_int/1, compare/2, reverse/1, break_tie/2, lazy_break_tie/2]). --export_type([order/0]). - --type order() :: lt | eq | gt. - --file("/Users/louis/src/gleam/stdlib/src/gleam/order.gleam", 35). --spec negate(order()) -> order(). -negate(Order) -> - case Order of - lt -> - gt; - - eq -> - eq; - - gt -> - lt - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/order.gleam", 62). --spec to_int(order()) -> integer(). -to_int(Order) -> - case Order of - lt -> - -1; - - eq -> - 0; - - gt -> - 1 - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/order.gleam", 79). --spec compare(order(), order()) -> order(). -compare(A, B) -> - case {A, B} of - {X, Y} when X =:= Y -> - eq; - - {lt, _} -> - lt; - - {eq, gt} -> - lt; - - {_, _} -> - gt - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/order.gleam", 100). --spec reverse(fun((I, I) -> order())) -> fun((I, I) -> order()). -reverse(Orderer) -> - fun(A, B) -> Orderer(B, A) end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/order.gleam", 122). --spec break_tie(order(), order()) -> order(). -break_tie(Order, Other) -> - case Order of - lt -> - Order; - - gt -> - Order; - - eq -> - Other - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/order.gleam", 151). --spec lazy_break_tie(order(), fun(() -> order())) -> order(). -lazy_break_tie(Order, Comparison) -> - case Order of - lt -> - Order; - - gt -> - Order; - - eq -> - Comparison() - end. diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@pair.erl b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@pair.erl deleted file mode 100644 index 160cfb98f80..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@pair.erl +++ /dev/null @@ -1,39 +0,0 @@ --module(gleam@pair). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([first/1, second/1, swap/1, map_first/2, map_second/2, new/2]). - --file("/Users/louis/src/gleam/stdlib/src/gleam/pair.gleam", 10). --spec first({YZ, any()}) -> YZ. -first(Pair) -> - {A, _} = Pair, - A. - --file("/Users/louis/src/gleam/stdlib/src/gleam/pair.gleam", 24). --spec second({any(), AAC}) -> AAC. -second(Pair) -> - {_, A} = Pair, - A. - --file("/Users/louis/src/gleam/stdlib/src/gleam/pair.gleam", 38). --spec swap({AAD, AAE}) -> {AAE, AAD}. -swap(Pair) -> - {A, B} = Pair, - {B, A}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/pair.gleam", 53). --spec map_first({AAF, AAG}, fun((AAF) -> AAH)) -> {AAH, AAG}. -map_first(Pair, Fun) -> - {A, B} = Pair, - {Fun(A), B}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/pair.gleam", 68). --spec map_second({AAI, AAJ}, fun((AAJ) -> AAK)) -> {AAI, AAK}. -map_second(Pair, Fun) -> - {A, B} = Pair, - {A, Fun(B)}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/pair.gleam", 83). --spec new(AAL, AAM) -> {AAL, AAM}. -new(First, Second) -> - {First, Second}. diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@queue.erl b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@queue.erl deleted file mode 100644 index 10012632bf5..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@queue.erl +++ /dev/null @@ -1,134 +0,0 @@ --module(gleam@queue). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([new/0, from_list/1, to_list/1, is_empty/1, length/1, push_back/2, push_front/2, pop_back/1, pop_front/1, reverse/1, is_logically_equal/3, is_equal/2]). --export_type([queue/1]). - --opaque queue(EXK) :: {queue, list(EXK), list(EXK)}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/queue.gleam", 22). --spec new() -> queue(any()). -new() -> - {queue, [], []}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/queue.gleam", 38). --spec from_list(list(EXN)) -> queue(EXN). -from_list(List) -> - {queue, [], List}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/queue.gleam", 54). --spec to_list(queue(EXQ)) -> list(EXQ). -to_list(Queue) -> - _pipe = erlang:element(3, Queue), - lists:append(_pipe, lists:reverse(erlang:element(2, Queue))). - --file("/Users/louis/src/gleam/stdlib/src/gleam/queue.gleam", 80). --spec is_empty(queue(any())) -> boolean(). -is_empty(Queue) -> - (erlang:element(2, Queue) =:= []) andalso (erlang:element(3, Queue) =:= []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/queue.gleam", 106). --spec length(queue(any())) -> integer(). -length(Queue) -> - erlang:length(erlang:element(2, Queue)) + erlang:length( - erlang:element(3, Queue) - ). - --file("/Users/louis/src/gleam/stdlib/src/gleam/queue.gleam", 119). --spec push_back(queue(EXX), EXX) -> queue(EXX). -push_back(Queue, Item) -> - {queue, [Item | erlang:element(2, Queue)], erlang:element(3, Queue)}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/queue.gleam", 132). --spec push_front(queue(EYA), EYA) -> queue(EYA). -push_front(Queue, Item) -> - {queue, erlang:element(2, Queue), [Item | erlang:element(3, Queue)]}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/queue.gleam", 164). --spec pop_back(queue(EYD)) -> {ok, {EYD, queue(EYD)}} | {error, nil}. -pop_back(Queue) -> - case Queue of - {queue, [], []} -> - {error, nil}; - - {queue, [], Out} -> - pop_back({queue, lists:reverse(Out), []}); - - {queue, [First | Rest], Out@1} -> - Queue@1 = {queue, Rest, Out@1}, - {ok, {First, Queue@1}} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/queue.gleam", 203). --spec pop_front(queue(EYI)) -> {ok, {EYI, queue(EYI)}} | {error, nil}. -pop_front(Queue) -> - case Queue of - {queue, [], []} -> - {error, nil}; - - {queue, In, []} -> - pop_front({queue, [], lists:reverse(In)}); - - {queue, In@1, [First | Rest]} -> - Queue@1 = {queue, In@1, Rest}, - {ok, {First, Queue@1}} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/queue.gleam", 236). --spec reverse(queue(EYN)) -> queue(EYN). -reverse(Queue) -> - {queue, erlang:element(3, Queue), erlang:element(2, Queue)}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/queue.gleam", 240). --spec check_equal( - list(EYQ), - list(EYQ), - list(EYQ), - list(EYQ), - fun((EYQ, EYQ) -> boolean()) -) -> boolean(). -check_equal(Xs, X_tail, Ys, Y_tail, Eq) -> - case {Xs, X_tail, Ys, Y_tail} of - {[], [], [], []} -> - true; - - {[X | Xs@1], _, [Y | Ys@1], _} -> - case Eq(X, Y) of - false -> - false; - - true -> - check_equal(Xs@1, X_tail, Ys@1, Y_tail, Eq) - end; - - {[], [_ | _], _, _} -> - check_equal(lists:reverse(X_tail), [], Ys, Y_tail, Eq); - - {_, _, [], [_ | _]} -> - check_equal(Xs, X_tail, lists:reverse(Y_tail), [], Eq); - - {_, _, _, _} -> - false - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/queue.gleam", 271). --spec is_logically_equal(queue(EYV), queue(EYV), fun((EYV, EYV) -> boolean())) -> boolean(). -is_logically_equal(A, B, Element_is_equal) -> - check_equal( - erlang:element(3, A), - erlang:element(2, A), - erlang:element(3, B), - erlang:element(2, B), - Element_is_equal - ). - --file("/Users/louis/src/gleam/stdlib/src/gleam/queue.gleam", 288). --spec is_equal(queue(EYY), queue(EYY)) -> boolean(). -is_equal(A, B) -> - check_equal( - erlang:element(3, A), - erlang:element(2, A), - erlang:element(3, B), - erlang:element(2, B), - fun(A@1, B@1) -> A@1 =:= B@1 end - ). diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@regex.erl b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@regex.erl deleted file mode 100644 index d3f32160afd..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@regex.erl +++ /dev/null @@ -1,43 +0,0 @@ --module(gleam@regex). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([compile/2, from_string/1, check/2, split/2, scan/2, replace/3]). --export_type([regex/0, match/0, compile_error/0, options/0]). - --type regex() :: any(). - --type match() :: {match, binary(), list(gleam@option:option(binary()))}. - --type compile_error() :: {compile_error, binary(), integer()}. - --type options() :: {options, boolean(), boolean()}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/regex.gleam", 55). --spec compile(binary(), options()) -> {ok, regex()} | {error, compile_error()}. -compile(Pattern, Options) -> - gleam_stdlib:compile_regex(Pattern, Options). - --file("/Users/louis/src/gleam/stdlib/src/gleam/regex.gleam", 92). --spec from_string(binary()) -> {ok, regex()} | {error, compile_error()}. -from_string(Pattern) -> - compile(Pattern, {options, false, false}). - --file("/Users/louis/src/gleam/stdlib/src/gleam/regex.gleam", 111). --spec check(regex(), binary()) -> boolean(). -check(Regex, String) -> - gleam_stdlib:regex_check(Regex, String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/regex.gleam", 129). --spec split(regex(), binary()) -> list(binary()). -split(Regex, String) -> - gleam_stdlib:regex_split(Regex, String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/regex.gleam", 189). --spec scan(regex(), binary()) -> list(match()). -scan(Regex, String) -> - gleam_stdlib:regex_scan(Regex, String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/regex.gleam", 215). --spec replace(regex(), binary(), binary()) -> binary(). -replace(Pattern, String, Substitute) -> - gleam_stdlib:regex_replace(Pattern, String, Substitute). diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@result.erl b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@result.erl deleted file mode 100644 index cfe30f62f9c..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@result.erl +++ /dev/null @@ -1,222 +0,0 @@ --module(gleam@result). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([is_ok/1, is_error/1, map/2, map_error/2, flatten/1, 'try'/2, then/2, unwrap/2, lazy_unwrap/2, unwrap_error/2, unwrap_both/1, nil_error/1, 'or'/2, lazy_or/2, all/1, partition/1, replace/2, replace_error/2, values/1, try_recover/2]). - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 20). --spec is_ok({ok, any()} | {error, any()}) -> boolean(). -is_ok(Result) -> - case Result of - {error, _} -> - false; - - {ok, _} -> - true - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 41). --spec is_error({ok, any()} | {error, any()}) -> boolean(). -is_error(Result) -> - case Result of - {ok, _} -> - false; - - {error, _} -> - true - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 66). --spec map({ok, BXE} | {error, BXF}, fun((BXE) -> BXI)) -> {ok, BXI} | - {error, BXF}. -map(Result, Fun) -> - case Result of - {ok, X} -> - {ok, Fun(X)}; - - {error, E} -> - {error, E} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 91). --spec map_error({ok, BXL} | {error, BXM}, fun((BXM) -> BXP)) -> {ok, BXL} | - {error, BXP}. -map_error(Result, Fun) -> - case Result of - {ok, X} -> - {ok, X}; - - {error, Error} -> - {error, Fun(Error)} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 120). --spec flatten({ok, {ok, BXS} | {error, BXT}} | {error, BXT}) -> {ok, BXS} | - {error, BXT}. -flatten(Result) -> - case Result of - {ok, X} -> - X; - - {error, Error} -> - {error, Error} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 158). --spec 'try'({ok, BYA} | {error, BYB}, fun((BYA) -> {ok, BYE} | {error, BYB})) -> {ok, - BYE} | - {error, BYB}. -'try'(Result, Fun) -> - case Result of - {ok, X} -> - Fun(X); - - {error, E} -> - {error, E} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 170). --spec then({ok, BYJ} | {error, BYK}, fun((BYJ) -> {ok, BYN} | {error, BYK})) -> {ok, - BYN} | - {error, BYK}. -then(Result, Fun) -> - 'try'(Result, Fun). - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 192). --spec unwrap({ok, BYS} | {error, any()}, BYS) -> BYS. -unwrap(Result, Default) -> - case Result of - {ok, V} -> - V; - - {error, _} -> - Default - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 214). --spec lazy_unwrap({ok, BYW} | {error, any()}, fun(() -> BYW)) -> BYW. -lazy_unwrap(Result, Default) -> - case Result of - {ok, V} -> - V; - - {error, _} -> - Default() - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 236). --spec unwrap_error({ok, any()} | {error, BZB}, BZB) -> BZB. -unwrap_error(Result, Default) -> - case Result of - {ok, _} -> - Default; - - {error, E} -> - E - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 258). --spec unwrap_both({ok, BZE} | {error, BZE}) -> BZE. -unwrap_both(Result) -> - case Result of - {ok, A} -> - A; - - {error, A@1} -> - A@1 - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 279). --spec nil_error({ok, BZH} | {error, any()}) -> {ok, BZH} | {error, nil}. -nil_error(Result) -> - map_error(Result, fun(_) -> nil end). - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 307). --spec 'or'({ok, BZN} | {error, BZO}, {ok, BZN} | {error, BZO}) -> {ok, BZN} | - {error, BZO}. -'or'(First, Second) -> - case First of - {ok, _} -> - First; - - {error, _} -> - Second - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 340). --spec lazy_or({ok, BZV} | {error, BZW}, fun(() -> {ok, BZV} | {error, BZW})) -> {ok, - BZV} | - {error, BZW}. -lazy_or(First, Second) -> - case First of - {ok, _} -> - First; - - {error, _} -> - Second() - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 366). --spec all(list({ok, CAD} | {error, CAE})) -> {ok, list(CAD)} | {error, CAE}. -all(Results) -> - gleam@list:try_map(Results, fun(X) -> X end). - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 386). --spec do_partition(list({ok, CAS} | {error, CAT}), list(CAS), list(CAT)) -> {list(CAS), - list(CAT)}. -do_partition(Results, Oks, Errors) -> - case Results of - [] -> - {Oks, Errors}; - - [{ok, A} | Rest] -> - do_partition(Rest, [A | Oks], Errors); - - [{error, E} | Rest@1] -> - do_partition(Rest@1, Oks, [E | Errors]) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 382). --spec partition(list({ok, CAL} | {error, CAM})) -> {list(CAL), list(CAM)}. -partition(Results) -> - do_partition(Results, [], []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 408). --spec replace({ok, any()} | {error, CBB}, CBE) -> {ok, CBE} | {error, CBB}. -replace(Result, Value) -> - case Result of - {ok, _} -> - {ok, Value}; - - {error, Error} -> - {error, Error} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 429). --spec replace_error({ok, CBH} | {error, any()}, CBL) -> {ok, CBH} | {error, CBL}. -replace_error(Result, Error) -> - case Result of - {ok, X} -> - {ok, X}; - - {error, _} -> - {error, Error} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 445). --spec values(list({ok, CBO} | {error, any()})) -> list(CBO). -values(Results) -> - gleam@list:filter_map(Results, fun(R) -> R end). - --file("/Users/louis/src/gleam/stdlib/src/gleam/result.gleam", 478). --spec try_recover( - {ok, CBU} | {error, CBV}, - fun((CBV) -> {ok, CBU} | {error, CBY}) -) -> {ok, CBU} | {error, CBY}. -try_recover(Result, Fun) -> - case Result of - {ok, Value} -> - {ok, Value}; - - {error, Error} -> - Fun(Error) - end. diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@set.erl b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@set.erl deleted file mode 100644 index 5aef9f27ec9..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@set.erl +++ /dev/null @@ -1,141 +0,0 @@ --module(gleam@set). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([new/0, size/1, is_empty/1, contains/2, delete/2, to_list/1, fold/3, filter/2, drop/2, take/2, intersection/2, difference/2, is_subset/2, is_disjoint/2, each/2, insert/2, from_list/1, map/2, union/2, symmetric_difference/2]). --export_type([set/1]). - --opaque set(FCW) :: {set, gleam@dict:dict(FCW, list(nil))}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 32). --spec new() -> set(any()). -new() -> - {set, gleam@dict:new()}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 50). --spec size(set(any())) -> integer(). -size(Set) -> - maps:size(erlang:element(2, Set)). - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 68). --spec is_empty(set(any())) -> boolean(). -is_empty(Set) -> - Set =:= new(). - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 110). --spec contains(set(FDH), FDH) -> boolean(). -contains(Set, Member) -> - _pipe = erlang:element(2, Set), - _pipe@1 = gleam@dict:get(_pipe, Member), - gleam@result:is_ok(_pipe@1). - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 131). --spec delete(set(FDJ), FDJ) -> set(FDJ). -delete(Set, Member) -> - {set, gleam@dict:delete(erlang:element(2, Set), Member)}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 149). --spec to_list(set(FDM)) -> list(FDM). -to_list(Set) -> - gleam@dict:keys(erlang:element(2, Set)). - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 190). --spec fold(set(FDS), FDU, fun((FDU, FDS) -> FDU)) -> FDU. -fold(Set, Initial, Reducer) -> - gleam@dict:fold( - erlang:element(2, Set), - Initial, - fun(A, K, _) -> Reducer(A, K) end - ). - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 214). --spec filter(set(FDV), fun((FDV) -> boolean())) -> set(FDV). -filter(Set, Predicate) -> - {set, - gleam@dict:filter(erlang:element(2, Set), fun(M, _) -> Predicate(M) end)}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 249). --spec drop(set(FEC), list(FEC)) -> set(FEC). -drop(Set, Disallowed) -> - gleam@list:fold(Disallowed, Set, fun delete/2). - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 267). --spec take(set(FEG), list(FEG)) -> set(FEG). -take(Set, Desired) -> - {set, gleam@dict:take(erlang:element(2, Set), Desired)}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 271). --spec order(set(FEK), set(FEK)) -> {set(FEK), set(FEK)}. -order(First, Second) -> - case maps:size(erlang:element(2, First)) > maps:size( - erlang:element(2, Second) - ) of - true -> - {First, Second}; - - false -> - {Second, First} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 305). --spec intersection(set(FET), set(FET)) -> set(FET). -intersection(First, Second) -> - {Larger, Smaller} = order(First, Second), - take(Larger, to_list(Smaller)). - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 323). --spec difference(set(FEX), set(FEX)) -> set(FEX). -difference(First, Second) -> - drop(First, to_list(Second)). - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 344). --spec is_subset(set(FFB), set(FFB)) -> boolean(). -is_subset(First, Second) -> - intersection(First, Second) =:= First. - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 362). --spec is_disjoint(set(FFE), set(FFE)) -> boolean(). -is_disjoint(First, Second) -> - intersection(First, Second) =:= new(). - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 402). --spec each(set(FFL), fun((FFL) -> any())) -> nil. -each(Set, Fun) -> - fold( - Set, - nil, - fun(Nil, Member) -> - Fun(Member), - Nil - end - ). - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 86). --spec insert(set(FDE), FDE) -> set(FDE). -insert(Set, Member) -> - {set, gleam@dict:insert(erlang:element(2, Set), Member, [])}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 167). --spec from_list(list(FDP)) -> set(FDP). -from_list(Members) -> - Dict = gleam@list:fold( - Members, - gleam@dict:new(), - fun(M, K) -> gleam@dict:insert(M, K, []) end - ), - {set, Dict}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 232). --spec map(set(FDY), fun((FDY) -> FEA)) -> set(FEA). -map(Set, Fun) -> - fold(Set, new(), fun(Acc, Member) -> insert(Acc, Fun(Member)) end). - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 289). --spec union(set(FEP), set(FEP)) -> set(FEP). -union(First, Second) -> - {Larger, Smaller} = order(First, Second), - fold(Smaller, Larger, fun insert/2). - --file("/Users/louis/src/gleam/stdlib/src/gleam/set.gleam", 374). --spec symmetric_difference(set(FFH), set(FFH)) -> set(FFH). -symmetric_difference(First, Second) -> - difference(union(First, Second), intersection(First, Second)). diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@string.erl b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@string.erl deleted file mode 100644 index f7a2ff89742..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@string.erl +++ /dev/null @@ -1,409 +0,0 @@ --module(gleam@string). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([is_empty/1, length/1, reverse/1, replace/3, lowercase/1, uppercase/1, compare/2, slice/3, crop/2, drop_left/2, drop_right/2, contains/2, starts_with/2, ends_with/2, split_once/2, append/2, concat/1, repeat/2, join/2, pad_left/3, pad_right/3, trim/1, trim_left/1, trim_right/1, pop_grapheme/1, to_graphemes/1, split/2, to_utf_codepoints/1, from_utf_codepoints/1, utf_codepoint/1, utf_codepoint_to_int/1, to_option/1, first/1, last/1, capitalise/1, inspect/1, byte_size/1]). --export_type([direction/0]). - --type direction() :: leading | trailing | both. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 23). --spec is_empty(binary()) -> boolean(). -is_empty(Str) -> - Str =:= <<""/utf8>>. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 49). --spec length(binary()) -> integer(). -length(String) -> - string:length(String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 73). --spec do_reverse(binary()) -> binary(). -do_reverse(String) -> - _pipe = String, - _pipe@1 = gleam@string_builder:from_string(_pipe), - _pipe@2 = gleam@string_builder:reverse(_pipe@1), - gleam@string_builder:to_string(_pipe@2). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 69). --spec reverse(binary()) -> binary(). -reverse(String) -> - do_reverse(String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 94). --spec replace(binary(), binary(), binary()) -> binary(). -replace(String, Pattern, Substitute) -> - _pipe = String, - _pipe@1 = gleam@string_builder:from_string(_pipe), - _pipe@2 = gleam_stdlib:string_replace(_pipe@1, Pattern, Substitute), - gleam@string_builder:to_string(_pipe@2). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 117). --spec lowercase(binary()) -> binary(). -lowercase(String) -> - string:lowercase(String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 137). --spec uppercase(binary()) -> binary(). -uppercase(String) -> - string:uppercase(String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 161). --spec compare(binary(), binary()) -> gleam@order:order(). -compare(A, B) -> - case A =:= B of - true -> - eq; - - _ -> - case gleam_stdlib:less_than(A, B) of - true -> - lt; - - _ -> - gt - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 206). --spec slice(binary(), integer(), integer()) -> binary(). -slice(String, Idx, Len) -> - case Len < 0 of - true -> - <<""/utf8>>; - - false -> - case Idx < 0 of - true -> - Translated_idx = length(String) + Idx, - case Translated_idx < 0 of - true -> - <<""/utf8>>; - - false -> - gleam_stdlib:slice(String, Translated_idx, Len) - end; - - false -> - gleam_stdlib:slice(String, Idx, Len) - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 239). --spec crop(binary(), binary()) -> binary(). -crop(String, Substring) -> - gleam_stdlib:crop_string(String, Substring). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 250). --spec drop_left(binary(), integer()) -> binary(). -drop_left(String, Num_graphemes) -> - case Num_graphemes < 0 of - true -> - String; - - false -> - slice(String, Num_graphemes, length(String) - Num_graphemes) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 266). --spec drop_right(binary(), integer()) -> binary(). -drop_right(String, Num_graphemes) -> - case Num_graphemes < 0 of - true -> - String; - - false -> - slice(String, 0, length(String) - Num_graphemes) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 294). --spec contains(binary(), binary()) -> boolean(). -contains(Haystack, Needle) -> - gleam_stdlib:contains_string(Haystack, Needle). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 305). --spec starts_with(binary(), binary()) -> boolean(). -starts_with(String, Prefix) -> - gleam_stdlib:string_starts_with(String, Prefix). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 322). --spec ends_with(binary(), binary()) -> boolean(). -ends_with(String, Suffix) -> - gleam_stdlib:string_ends_with(String, Suffix). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 374). --spec do_split_once(binary(), binary()) -> {ok, {binary(), binary()}} | - {error, nil}. -do_split_once(String, Substring) -> - case string:split(String, Substring) of - [First, Rest] -> - {ok, {First, Rest}}; - - _ -> - {error, nil} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 366). --spec split_once(binary(), binary()) -> {ok, {binary(), binary()}} | - {error, nil}. -split_once(String, Substring) -> - do_split_once(String, Substring). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 400). --spec append(binary(), binary()) -> binary(). -append(First, Second) -> - _pipe = First, - _pipe@1 = gleam@string_builder:from_string(_pipe), - _pipe@2 = gleam@string_builder:append(_pipe@1, Second), - gleam@string_builder:to_string(_pipe@2). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 420). --spec concat(list(binary())) -> binary(). -concat(Strings) -> - _pipe = Strings, - _pipe@1 = gleam@string_builder:from_strings(_pipe), - gleam@string_builder:to_string(_pipe@1). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 441). --spec do_repeat(binary(), integer(), binary()) -> binary(). -do_repeat(String, Times, Acc) -> - case Times =< 0 of - true -> - Acc; - - false -> - do_repeat(String, Times - 1, <>) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 437). --spec repeat(binary(), integer()) -> binary(). -repeat(String, Times) -> - do_repeat(String, Times, <<""/utf8>>). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 464). --spec do_join(list(binary()), binary()) -> binary(). -do_join(Strings, Separator) -> - _pipe = Strings, - _pipe@1 = gleam@list:intersperse(_pipe, Separator), - concat(_pipe@1). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 459). --spec join(list(binary()), binary()) -> binary(). -join(Strings, Separator) -> - do_join(Strings, Separator). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 536). --spec padding(integer(), binary()) -> binary(). -padding(Size, Pad_string) -> - Pad_string_length = length(Pad_string), - Num_pads = case Pad_string_length of - 0 -> 0; - Gleam@denominator -> Size div Gleam@denominator - end, - Extra = case Pad_string_length of - 0 -> 0; - Gleam@denominator@1 -> Size rem Gleam@denominator@1 - end, - <<(repeat(Pad_string, Num_pads))/binary, - (slice(Pad_string, 0, Extra))/binary>>. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 489). --spec pad_left(binary(), integer(), binary()) -> binary(). -pad_left(String, Desired_length, Pad_string) -> - Current_length = length(String), - To_pad_length = Desired_length - Current_length, - case To_pad_length =< 0 of - true -> - String; - - false -> - <<(padding(To_pad_length, Pad_string))/binary, String/binary>> - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 522). --spec pad_right(binary(), integer(), binary()) -> binary(). -pad_right(String, Desired_length, Pad_string) -> - Current_length = length(String), - To_pad_length = Desired_length - Current_length, - case To_pad_length =< 0 of - true -> - String; - - false -> - <> - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 558). --spec do_trim(binary()) -> binary(). -do_trim(String) -> - string:trim(String, both). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 553). --spec trim(binary()) -> binary(). -trim(String) -> - do_trim(String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 585). --spec do_trim_left(binary()) -> binary(). -do_trim_left(String) -> - string:trim(String, leading). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 580). --spec trim_left(binary()) -> binary(). -trim_left(String) -> - do_trim_left(String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 603). --spec do_trim_right(binary()) -> binary(). -do_trim_right(String) -> - string:trim(String, trailing). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 598). --spec trim_right(binary()) -> binary(). -trim_right(String) -> - do_trim_right(String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 626). --spec pop_grapheme(binary()) -> {ok, {binary(), binary()}} | {error, nil}. -pop_grapheme(String) -> - gleam_stdlib:string_pop_grapheme(String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 648). --spec do_to_graphemes(binary(), list(binary())) -> list(binary()). -do_to_graphemes(String, Acc) -> - case pop_grapheme(String) of - {ok, {Grapheme, Rest}} -> - do_to_graphemes(Rest, [Grapheme | Acc]); - - _ -> - Acc - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 643). --spec to_graphemes(binary()) -> list(binary()). -to_graphemes(String) -> - _pipe = do_to_graphemes(String, []), - lists:reverse(_pipe). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 339). --spec split(binary(), binary()) -> list(binary()). -split(X, Substring) -> - case Substring of - <<""/utf8>> -> - to_graphemes(X); - - _ -> - _pipe = X, - _pipe@1 = gleam@string_builder:from_string(_pipe), - _pipe@2 = gleam@string_builder:split(_pipe@1, Substring), - gleam@list:map(_pipe@2, fun gleam@string_builder:to_string/1) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 696). --spec do_to_utf_codepoints_impl(bitstring(), list(integer())) -> list(integer()). -do_to_utf_codepoints_impl(Bit_array, Acc) -> - case Bit_array of - <> -> - do_to_utf_codepoints_impl(Rest, [First | Acc]); - - _ -> - Acc - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 690). --spec do_to_utf_codepoints(binary()) -> list(integer()). -do_to_utf_codepoints(String) -> - _pipe = do_to_utf_codepoints_impl(<>, []), - lists:reverse(_pipe). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 685). --spec to_utf_codepoints(binary()) -> list(integer()). -to_utf_codepoints(String) -> - do_to_utf_codepoints(String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 736). --spec from_utf_codepoints(list(integer())) -> binary(). -from_utf_codepoints(Utf_codepoints) -> - gleam_stdlib:utf_codepoint_list_to_string(Utf_codepoints). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 742). --spec utf_codepoint(integer()) -> {ok, integer()} | {error, nil}. -utf_codepoint(Value) -> - case Value of - I when I > 1114111 -> - {error, nil}; - - 65534 -> - {error, nil}; - - 65535 -> - {error, nil}; - - I@1 when (I@1 >= 55296) andalso (I@1 =< 57343) -> - {error, nil}; - - I@2 -> - {ok, gleam_stdlib:identity(I@2)} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 761). --spec utf_codepoint_to_int(integer()) -> integer(). -utf_codepoint_to_int(Cp) -> - gleam_stdlib:identity(Cp). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 784). --spec to_option(binary()) -> gleam@option:option(binary()). -to_option(String) -> - case String of - <<""/utf8>> -> - none; - - _ -> - {some, String} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 807). --spec first(binary()) -> {ok, binary()} | {error, nil}. -first(String) -> - case pop_grapheme(String) of - {ok, {First, _}} -> - {ok, First}; - - {error, E} -> - {error, E} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 830). --spec last(binary()) -> {ok, binary()} | {error, nil}. -last(String) -> - case pop_grapheme(String) of - {ok, {First, <<""/utf8>>}} -> - {ok, First}; - - {ok, {_, Rest}} -> - {ok, slice(Rest, -1, 1)}; - - {error, E} -> - {error, E} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 848). --spec capitalise(binary()) -> binary(). -capitalise(String) -> - case pop_grapheme(String) of - {ok, {First, Rest}} -> - append(uppercase(First), lowercase(Rest)); - - _ -> - <<""/utf8>> - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 857). --spec inspect(any()) -> binary(). -inspect(Term) -> - _pipe = gleam_stdlib:inspect(Term), - gleam@string_builder:to_string(_pipe). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string.gleam", 880). --spec byte_size(binary()) -> integer(). -byte_size(String) -> - erlang:byte_size(String). diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@string_builder.erl b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@string_builder.erl deleted file mode 100644 index ce421cb8520..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@string_builder.erl +++ /dev/null @@ -1,106 +0,0 @@ --module(gleam@string_builder). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([prepend_builder/2, append_builder/2, new/0, from_strings/1, concat/1, from_string/1, prepend/2, append/2, to_string/1, byte_size/1, join/2, lowercase/1, uppercase/1, reverse/1, split/2, replace/3, is_equal/2, is_empty/1]). --export_type([string_builder/0, direction/0]). - --type string_builder() :: any(). - --type direction() :: all. - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 51). --spec prepend_builder(string_builder(), string_builder()) -> string_builder(). -prepend_builder(Builder, Prefix) -> - gleam_stdlib:iodata_append(Prefix, Builder). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 62). --spec append_builder(string_builder(), string_builder()) -> string_builder(). -append_builder(Builder, Suffix) -> - gleam_stdlib:iodata_append(Builder, Suffix). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 24). --spec new() -> string_builder(). -new() -> - gleam_stdlib:identity([]). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 77). --spec from_strings(list(binary())) -> string_builder(). -from_strings(Strings) -> - gleam_stdlib:identity(Strings). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 89). --spec concat(list(string_builder())) -> string_builder(). -concat(Builders) -> - gleam_stdlib:identity(Builders). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 101). --spec from_string(binary()) -> string_builder(). -from_string(String) -> - gleam_stdlib:identity(String). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 32). --spec prepend(string_builder(), binary()) -> string_builder(). -prepend(Builder, Prefix) -> - append_builder(from_string(Prefix), Builder). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 43). --spec append(string_builder(), binary()) -> string_builder(). -append(Builder, Second) -> - append_builder(Builder, from_string(Second)). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 114). --spec to_string(string_builder()) -> binary(). -to_string(Builder) -> - unicode:characters_to_binary(Builder). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 124). --spec byte_size(string_builder()) -> integer(). -byte_size(Builder) -> - erlang:iolist_size(Builder). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 134). --spec join(list(string_builder()), binary()) -> string_builder(). -join(Builders, Sep) -> - _pipe = Builders, - _pipe@1 = gleam@list:intersperse(_pipe, from_string(Sep)), - concat(_pipe@1). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 143). --spec lowercase(string_builder()) -> string_builder(). -lowercase(Builder) -> - string:lowercase(Builder). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 154). --spec uppercase(string_builder()) -> string_builder(). -uppercase(Builder) -> - string:uppercase(Builder). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 164). --spec reverse(string_builder()) -> string_builder(). -reverse(Builder) -> - string:reverse(Builder). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 191). --spec do_split(string_builder(), binary()) -> list(string_builder()). -do_split(Iodata, Pattern) -> - string:split(Iodata, Pattern, all). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 182). --spec split(string_builder(), binary()) -> list(string_builder()). -split(Iodata, Pattern) -> - do_split(Iodata, Pattern). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 202). --spec replace(string_builder(), binary(), binary()) -> string_builder(). -replace(Builder, Pattern, Substitute) -> - gleam_stdlib:string_replace(Builder, Pattern, Substitute). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 227). --spec is_equal(string_builder(), string_builder()) -> boolean(). -is_equal(A, B) -> - string:equal(A, B). - --file("/Users/louis/src/gleam/stdlib/src/gleam/string_builder.gleam", 251). --spec is_empty(string_builder()) -> boolean(). -is_empty(Builder) -> - string:is_empty(Builder). diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@uri.erl b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@uri.erl deleted file mode 100644 index b6d300f5616..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam@uri.erl +++ /dev/null @@ -1,376 +0,0 @@ --module(gleam@uri). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([parse/1, parse_query/1, percent_encode/1, query_to_string/1, percent_decode/1, path_segments/1, to_string/1, origin/1, merge/2]). --export_type([uri/0]). - --type uri() :: {uri, - gleam@option:option(binary()), - gleam@option:option(binary()), - gleam@option:option(binary()), - gleam@option:option(integer()), - binary(), - gleam@option:option(binary()), - gleam@option:option(binary())}. - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 116). --spec regex_submatches(binary(), binary()) -> list(gleam@option:option(binary())). -regex_submatches(Pattern, String) -> - _pipe = Pattern, - _pipe@1 = gleam@regex:compile(_pipe, {options, true, false}), - _pipe@2 = gleam@result:nil_error(_pipe@1), - _pipe@3 = gleam@result:map( - _pipe@2, - fun(_capture) -> gleam@regex:scan(_capture, String) end - ), - _pipe@4 = gleam@result:'try'(_pipe@3, fun gleam@list:first/1), - _pipe@5 = gleam@result:map(_pipe@4, fun(M) -> erlang:element(3, M) end), - gleam@result:unwrap(_pipe@5, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 126). --spec noneify_query(gleam@option:option(binary())) -> gleam@option:option(binary()). -noneify_query(X) -> - case X of - none -> - none; - - {some, X@1} -> - case gleam@string:pop_grapheme(X@1) of - {ok, {<<"?"/utf8>>, Query}} -> - {some, Query}; - - _ -> - none - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 137). --spec noneify_empty_string(gleam@option:option(binary())) -> gleam@option:option(binary()). -noneify_empty_string(X) -> - case X of - {some, <<""/utf8>>} -> - none; - - none -> - none; - - {some, _} -> - X - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 178). --spec extra_required(list(any()), integer()) -> integer(). -extra_required(List, Remaining) -> - case List of - _ when Remaining =:= 0 -> - 0; - - [] -> - Remaining; - - [_ | Rest] -> - extra_required(Rest, Remaining - 1) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 173). --spec pad_list(list(gleam@option:option(FJT)), integer()) -> list(gleam@option:option(FJT)). -pad_list(List, Size) -> - _pipe = List, - lists:append(_pipe, gleam@list:repeat(none, extra_required(List, Size))). - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 145). --spec split_authority(gleam@option:option(binary())) -> {gleam@option:option(binary()), - gleam@option:option(binary()), - gleam@option:option(integer())}. -split_authority(Authority) -> - case gleam@option:unwrap(Authority, <<""/utf8>>) of - <<""/utf8>> -> - {none, none, none}; - - <<"//"/utf8>> -> - {none, {some, <<""/utf8>>}, none}; - - Authority@1 -> - Matches = begin - _pipe = <<"^(//)?((.*)@)?(\\[[a-zA-Z0-9:.]*\\]|[^:]*)(:(\\d*))?"/utf8>>, - _pipe@1 = regex_submatches(_pipe, Authority@1), - pad_list(_pipe@1, 6) - end, - case Matches of - [_, _, Userinfo, Host, _, Port] -> - Userinfo@1 = noneify_empty_string(Userinfo), - Host@1 = noneify_empty_string(Host), - Port@1 = begin - _pipe@2 = Port, - _pipe@3 = gleam@option:unwrap(_pipe@2, <<""/utf8>>), - _pipe@4 = gleam@int:parse(_pipe@3), - gleam@option:from_result(_pipe@4) - end, - {Userinfo@1, Host@1, Port@1}; - - _ -> - {none, none, none} - end - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 56). --spec parse(binary()) -> {ok, uri()} | {error, nil}. -parse(Uri_string) -> - gleam_stdlib:uri_parse(Uri_string). - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 198). --spec parse_query(binary()) -> {ok, list({binary(), binary()})} | {error, nil}. -parse_query(Query) -> - gleam_stdlib:parse_query(Query). - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 242). --spec percent_encode(binary()) -> binary(). -percent_encode(Value) -> - gleam_stdlib:percent_encode(Value). - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 225). --spec query_pair({binary(), binary()}) -> gleam@string_builder:string_builder(). -query_pair(Pair) -> - gleam@string_builder:from_strings( - [percent_encode(erlang:element(1, Pair)), - <<"="/utf8>>, - percent_encode(erlang:element(2, Pair))] - ). - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 217). --spec query_to_string(list({binary(), binary()})) -> binary(). -query_to_string(Query) -> - _pipe = Query, - _pipe@1 = gleam@list:map(_pipe, fun query_pair/1), - _pipe@2 = gleam@list:intersperse( - _pipe@1, - gleam@string_builder:from_string(<<"&"/utf8>>) - ), - _pipe@3 = gleam@string_builder:concat(_pipe@2), - gleam@string_builder:to_string(_pipe@3). - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 259). --spec percent_decode(binary()) -> {ok, binary()} | {error, nil}. -percent_decode(Value) -> - gleam_stdlib:percent_decode(Value). - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 267). --spec do_remove_dot_segments(list(binary()), list(binary())) -> list(binary()). -do_remove_dot_segments(Input, Accumulator) -> - case Input of - [] -> - lists:reverse(Accumulator); - - [Segment | Rest] -> - Accumulator@5 = case {Segment, Accumulator} of - {<<""/utf8>>, Accumulator@1} -> - Accumulator@1; - - {<<"."/utf8>>, Accumulator@2} -> - Accumulator@2; - - {<<".."/utf8>>, []} -> - []; - - {<<".."/utf8>>, [_ | Accumulator@3]} -> - Accumulator@3; - - {Segment@1, Accumulator@4} -> - [Segment@1 | Accumulator@4] - end, - do_remove_dot_segments(Rest, Accumulator@5) - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 286). --spec remove_dot_segments(list(binary())) -> list(binary()). -remove_dot_segments(Input) -> - do_remove_dot_segments(Input, []). - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 302). --spec path_segments(binary()) -> list(binary()). -path_segments(Path) -> - remove_dot_segments(gleam@string:split(Path, <<"/"/utf8>>)). - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 318). --spec to_string(uri()) -> binary(). -to_string(Uri) -> - Parts = case erlang:element(8, Uri) of - {some, Fragment} -> - [<<"#"/utf8>>, Fragment]; - - _ -> - [] - end, - Parts@1 = case erlang:element(7, Uri) of - {some, Query} -> - [<<"?"/utf8>>, Query | Parts]; - - _ -> - Parts - end, - Parts@2 = [erlang:element(6, Uri) | Parts@1], - Parts@3 = case {erlang:element(4, Uri), - gleam@string:starts_with(erlang:element(6, Uri), <<"/"/utf8>>)} of - {{some, Host}, false} when Host =/= <<""/utf8>> -> - [<<"/"/utf8>> | Parts@2]; - - {_, _} -> - Parts@2 - end, - Parts@4 = case {erlang:element(4, Uri), erlang:element(5, Uri)} of - {{some, _}, {some, Port}} -> - [<<":"/utf8>>, gleam@int:to_string(Port) | Parts@3]; - - {_, _} -> - Parts@3 - end, - Parts@5 = case {erlang:element(2, Uri), - erlang:element(3, Uri), - erlang:element(4, Uri)} of - {{some, S}, {some, U}, {some, H}} -> - [S, <<"://"/utf8>>, U, <<"@"/utf8>>, H | Parts@4]; - - {{some, S@1}, none, {some, H@1}} -> - [S@1, <<"://"/utf8>>, H@1 | Parts@4]; - - {{some, S@2}, {some, _}, none} -> - [S@2, <<":"/utf8>> | Parts@4]; - - {{some, S@2}, none, none} -> - [S@2, <<":"/utf8>> | Parts@4]; - - {none, none, {some, H@2}} -> - [<<"//"/utf8>>, H@2 | Parts@4]; - - {_, _, _} -> - Parts@4 - end, - gleam@string:concat(Parts@5). - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 362). --spec origin(uri()) -> {ok, binary()} | {error, nil}. -origin(Uri) -> - {uri, Scheme, _, Host, Port, _, _, _} = Uri, - case {Host, Scheme} of - {{some, H}, {some, <<"https"/utf8>>}} when Port =:= {some, 443} -> - {ok, gleam@string:concat([<<"https://"/utf8>>, H])}; - - {{some, H@1}, {some, <<"http"/utf8>>}} when Port =:= {some, 80} -> - {ok, gleam@string:concat([<<"http://"/utf8>>, H@1])}; - - {{some, H@2}, {some, S}} when (S =:= <<"http"/utf8>>) orelse (S =:= <<"https"/utf8>>) -> - case Port of - {some, P} -> - {ok, - gleam@string:concat( - [S, - <<"://"/utf8>>, - H@2, - <<":"/utf8>>, - gleam@int:to_string(P)] - )}; - - none -> - {ok, gleam@string:concat([S, <<"://"/utf8>>, H@2])} - end; - - {_, _} -> - {error, nil} - end. - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 379). --spec drop_last(list(FKT)) -> list(FKT). -drop_last(Elements) -> - gleam@list:take(Elements, erlang:length(Elements) - 1). - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 383). --spec join_segments(list(binary())) -> binary(). -join_segments(Segments) -> - gleam@string:join([<<""/utf8>> | Segments], <<"/"/utf8>>). - --file("/Users/louis/src/gleam/stdlib/src/gleam/uri.gleam", 393). --spec merge(uri(), uri()) -> {ok, uri()} | {error, nil}. -merge(Base, Relative) -> - case Base of - {uri, {some, _}, _, {some, _}, _, _, _, _} -> - case Relative of - {uri, _, _, {some, _}, _, _, _, _} -> - Path = begin - _pipe = gleam@string:split( - erlang:element(6, Relative), - <<"/"/utf8>> - ), - _pipe@1 = remove_dot_segments(_pipe), - join_segments(_pipe@1) - end, - Resolved = {uri, - gleam@option:'or'( - erlang:element(2, Relative), - erlang:element(2, Base) - ), - none, - erlang:element(4, Relative), - gleam@option:'or'( - erlang:element(5, Relative), - erlang:element(5, Base) - ), - Path, - erlang:element(7, Relative), - erlang:element(8, Relative)}, - {ok, Resolved}; - - _ -> - {New_path, New_query} = case erlang:element(6, Relative) of - <<""/utf8>> -> - {erlang:element(6, Base), - gleam@option:'or'( - erlang:element(7, Relative), - erlang:element(7, Base) - )}; - - _ -> - Path_segments = case gleam@string:starts_with( - erlang:element(6, Relative), - <<"/"/utf8>> - ) of - true -> - gleam@string:split( - erlang:element(6, Relative), - <<"/"/utf8>> - ); - - false -> - _pipe@2 = gleam@string:split( - erlang:element(6, Base), - <<"/"/utf8>> - ), - _pipe@3 = drop_last(_pipe@2), - lists:append( - _pipe@3, - gleam@string:split( - erlang:element(6, Relative), - <<"/"/utf8>> - ) - ) - end, - Path@1 = begin - _pipe@4 = Path_segments, - _pipe@5 = remove_dot_segments(_pipe@4), - join_segments(_pipe@5) - end, - {Path@1, erlang:element(7, Relative)} - end, - Resolved@1 = {uri, - erlang:element(2, Base), - none, - erlang:element(4, Base), - erlang:element(5, Base), - New_path, - New_query, - erlang:element(8, Relative)}, - {ok, Resolved@1} - end; - - _ -> - {error, nil} - end. diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam_stdlib.app.src b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam_stdlib.app.src deleted file mode 100644 index 88c7f140d57..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam_stdlib.app.src +++ /dev/null @@ -1,27 +0,0 @@ -{application, gleam_stdlib, [ - {vsn, "0.41.0"}, - {applications, []}, - {description, "A standard library for the Gleam programming language"}, - {modules, [gleam@bit_array, - gleam@bool, - gleam@bytes_builder, - gleam@dict, - gleam@dynamic, - gleam@float, - gleam@function, - gleam@int, - gleam@io, - gleam@iterator, - gleam@list, - gleam@option, - gleam@order, - gleam@pair, - gleam@queue, - gleam@regex, - gleam@result, - gleam@set, - gleam@string, - gleam@string_builder, - gleam@uri]}, - {registered, []} -]}. diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam_stdlib.erl b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam_stdlib.erl deleted file mode 100644 index 562ef2372a2..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam_stdlib.erl +++ /dev/null @@ -1,565 +0,0 @@ --module(gleam_stdlib). - --export([ - map_get/2, iodata_append/2, identity/1, decode_int/1, decode_bool/1, - decode_float/1, decode_list/1, decode_option/2, decode_field/2, parse_int/1, - parse_float/1, less_than/2, string_pop_grapheme/1, string_starts_with/2, - wrap_list/1, string_ends_with/2, string_pad/4, decode_map/1, uri_parse/1, - bit_array_int_to_u32/1, bit_array_int_from_u32/1, decode_result/1, - bit_array_slice/3, decode_bit_array/1, compile_regex/2, regex_scan/2, - percent_encode/1, percent_decode/1, regex_check/2, regex_split/2, - base_decode64/1, parse_query/1, bit_array_concat/1, - bit_array_base64_encode/2, size_of_tuple/1, - decode_tuple/1, decode_tuple2/1, decode_tuple3/1, decode_tuple4/1, - decode_tuple5/1, decode_tuple6/1, tuple_get/2, classify_dynamic/1, print/1, - println/1, print_error/1, println_error/1, inspect/1, float_to_string/1, - int_from_base_string/2, utf_codepoint_list_to_string/1, contains_string/2, - crop_string/2, base16_decode/1, string_replace/3, regex_replace/3, slice/3, bit_array_to_int_and_size/1 -]). - -%% Taken from OTP's uri_string module --define(DEC2HEX(X), - if ((X) >= 0) andalso ((X) =< 9) -> (X) + $0; - ((X) >= 10) andalso ((X) =< 15) -> (X) + $A - 10 - end). - -%% Taken from OTP's uri_string module --define(HEX2DEC(X), - if ((X) >= $0) andalso ((X) =< $9) -> (X) - $0; - ((X) >= $A) andalso ((X) =< $F) -> (X) - $A + 10; - ((X) >= $a) andalso ((X) =< $f) -> (X) - $a + 10 - end). - --define(is_lowercase_char(X), (X > 96 andalso X < 123)). --define(is_underscore_char(X), (X == 95)). --define(is_digit_char(X), (X > 47 andalso X < 58)). - -uppercase(X) -> X - 32. - -map_get(Map, Key) -> - case maps:find(Key, Map) of - error -> {error, nil}; - OkFound -> OkFound - end. - -iodata_append(Iodata, String) -> [Iodata, String]. - -identity(X) -> X. - -decode_error_msg(Expected, Data) when is_binary(Expected) -> - decode_error(Expected, classify_dynamic(Data)). -decode_error(Expected, Got) when is_binary(Expected) andalso is_binary(Got) -> - {error, [{decode_error, Expected, Got, []}]}. - -classify_dynamic(nil) -> <<"Nil">>; -classify_dynamic(X) when is_boolean(X) -> <<"Bool">>; -classify_dynamic(X) when is_atom(X) -> <<"Atom">>; -classify_dynamic(X) when is_binary(X) -> <<"String">>; -classify_dynamic(X) when is_bitstring(X) -> <<"BitArray">>; -classify_dynamic(X) when is_integer(X) -> <<"Int">>; -classify_dynamic(X) when is_float(X) -> <<"Float">>; -classify_dynamic(X) when is_list(X) -> <<"List">>; -classify_dynamic(X) when is_map(X) -> <<"Dict">>; -classify_dynamic(X) when is_tuple(X) -> - iolist_to_binary(["Tuple of ", integer_to_list(tuple_size(X)), " elements"]); -classify_dynamic(X) when - is_function(X, 0) orelse is_function(X, 1) orelse is_function(X, 2) orelse - is_function(X, 3) orelse is_function(X, 4) orelse is_function(X, 5) orelse - is_function(X, 6) orelse is_function(X, 7) orelse is_function(X, 8) orelse - is_function(X, 9) orelse is_function(X, 10) orelse is_function(X, 11) orelse - is_function(X, 12) -> <<"Function">>; -classify_dynamic(_) -> <<"Some other type">>. - -decode_map(Data) when is_map(Data) -> {ok, Data}; -decode_map(Data) -> decode_error_msg(<<"Dict">>, Data). - -decode_bit_array(Data) when is_bitstring(Data) -> {ok, Data}; -decode_bit_array(Data) -> decode_error_msg(<<"BitArray">>, Data). - -decode_int(Data) when is_integer(Data) -> {ok, Data}; -decode_int(Data) -> decode_error_msg(<<"Int">>, Data). - -decode_float(Data) when is_float(Data) -> {ok, Data}; -decode_float(Data) -> decode_error_msg(<<"Float">>, Data). - -decode_bool(Data) when is_boolean(Data) -> {ok, Data}; -decode_bool(Data) -> decode_error_msg(<<"Bool">>, Data). - -decode_list(Data) when is_list(Data) -> {ok, Data}; -decode_list(Data) -> decode_error_msg(<<"List">>, Data). - -decode_field(Data, Key) when is_map(Data) -> - case Data of - #{Key := Value} -> {ok, {some, Value}}; - _ -> - {ok, none} - end; -decode_field(Data, _) -> - decode_error_msg(<<"Dict">>, Data). - -size_of_tuple(Data) -> tuple_size(Data). - -tuple_get(_tup, Index) when Index < 0 -> {error, nil}; -tuple_get(Data, Index) when Index >= tuple_size(Data) -> {error, nil}; -tuple_get(Data, Index) -> {ok, element(Index + 1, Data)}. - -decode_tuple(Data) when is_tuple(Data) -> {ok, Data}; -decode_tuple(Data) -> decode_error_msg(<<"Tuple">>, Data). - -decode_tuple2({_,_} = A) -> {ok, A}; -decode_tuple2([A,B]) -> {ok, {A,B}}; -decode_tuple2(Data) -> decode_error_msg(<<"Tuple of 2 elements">>, Data). - -decode_tuple3({_,_,_} = A) -> {ok, A}; -decode_tuple3([A,B,C]) -> {ok, {A,B,C}}; -decode_tuple3(Data) -> decode_error_msg(<<"Tuple of 3 elements">>, Data). - -decode_tuple4({_,_,_,_} = A) -> {ok, A}; -decode_tuple4([A,B,C,D]) -> {ok, {A,B,C,D}}; -decode_tuple4(Data) -> decode_error_msg(<<"Tuple of 4 elements">>, Data). - -decode_tuple5({_,_,_,_,_} = A) -> {ok, A}; -decode_tuple5([A,B,C,D,E]) -> {ok, {A,B,C,D,E}}; -decode_tuple5(Data) -> decode_error_msg(<<"Tuple of 5 elements">>, Data). - -decode_tuple6({_,_,_,_,_,_} = A) -> {ok, A}; -decode_tuple6([A,B,C,D,E,F]) -> {ok, {A,B,C,D,E,F}}; -decode_tuple6(Data) -> decode_error_msg(<<"Tuple of 6 elements">>, Data). - -decode_option(Term, F) -> - Decode = fun(Inner) -> - case F(Inner) of - {ok, Decoded} -> {ok, {some, Decoded}}; - Error -> Error - end - end, - case Term of - undefined -> {ok, none}; - error -> {ok, none}; - null -> {ok, none}; - none -> {ok, none}; - nil -> {ok, none}; - {some, Inner} -> Decode(Inner); - _ -> Decode(Term) - end. - -decode_result(Term) -> - case Term of - {ok, Inner} -> {ok, {ok, Inner}}; - ok -> {ok, {ok, nil}}; - {error, Inner} -> {ok, {error, Inner}}; - error -> {ok, {error, nil}}; - _ -> decode_error_msg(<<"Result">>, Term) - end. - -int_from_base_string(String, Base) -> - case catch binary_to_integer(String, Base) of - Int when is_integer(Int) -> {ok, Int}; - _ -> {error, nil} - end. - -parse_int(String) -> - case catch binary_to_integer(String) of - Int when is_integer(Int) -> {ok, Int}; - _ -> {error, nil} - end. - -parse_float(String) -> - case catch binary_to_float(String) of - Float when is_float(Float) -> {ok, Float}; - _ -> {error, nil} - end. - -less_than(Lhs, Rhs) -> - Lhs < Rhs. - -string_starts_with(_, <<>>) -> true; -string_starts_with(String, Prefix) when byte_size(Prefix) > byte_size(String) -> false; -string_starts_with(String, Prefix) -> - PrefixSize = byte_size(Prefix), - Prefix == binary_part(String, 0, PrefixSize). - -string_ends_with(_, <<>>) -> true; -string_ends_with(String, Suffix) when byte_size(Suffix) > byte_size(String) -> false; -string_ends_with(String, Suffix) -> - SuffixSize = byte_size(Suffix), - Suffix == binary_part(String, byte_size(String) - SuffixSize, SuffixSize). - -string_pad(String, Length, Dir, PadString) -> - Chars = string:pad(String, Length, Dir, binary_to_list(PadString)), - case unicode:characters_to_binary(Chars) of - Bin when is_binary(Bin) -> Bin; - Error -> erlang:error({gleam_error, {string_invalid_utf8, Error}}) - end. - -string_pop_grapheme(String) -> - case string:next_grapheme(String) of - [ Next | Rest ] when is_binary(Rest) -> - {ok, {unicode:characters_to_binary([Next]), Rest}}; - - [ Next | Rest ] -> - {ok, {unicode:characters_to_binary([Next]), unicode:characters_to_binary(Rest)}}; - - _ -> {error, nil} - end. - -bit_array_concat(BitArrays) -> - list_to_bitstring(BitArrays). - --if(?OTP_RELEASE >= 26). -bit_array_base64_encode(Bin, Padding) -> - base64:encode(Bin, #{padding => Padding}). --else. -bit_array_base64_encode(_Bin, _Padding) -> - erlang:error(<<"Erlang OTP/26 or higher is required to use base64:encode">>). --endif. - -bit_array_slice(Bin, Pos, Len) -> - try {ok, binary:part(Bin, Pos, Len)} - catch error:badarg -> {error, nil} - end. - -bit_array_int_to_u32(I) when 0 =< I, I < 4294967296 -> - {ok, <>}; -bit_array_int_to_u32(_) -> - {error, nil}. - -bit_array_int_from_u32(<>) -> - {ok, I}; -bit_array_int_from_u32(_) -> - {error, nil}. - -compile_regex(String, Options) -> - {options, Caseless, Multiline} = Options, - OptionsList = [ - unicode, - ucp, - Caseless andalso caseless, - Multiline andalso multiline - ], - FilteredOptions = [Option || Option <- OptionsList, Option /= false], - case re:compile(String, FilteredOptions) of - {ok, MP} -> {ok, MP}; - {error, {Str, Pos}} -> - {error, {compile_error, unicode:characters_to_binary(Str), Pos}} - end. - -regex_check(Regex, String) -> - re:run(String, Regex) /= nomatch. - -regex_split(Regex, String) -> - re:split(String, Regex). - -regex_submatches(_, {-1, 0}) -> none; -regex_submatches(String, {Start, Length}) -> - BinarySlice = binary:part(String, {Start, Length}), - case string:is_empty(binary_to_list(BinarySlice)) of - true -> none; - false -> {some, BinarySlice} - end. - -regex_matches(String, [{Start, Length} | Submatches]) -> - Submatches1 = lists:map(fun(X) -> regex_submatches(String, X) end, Submatches), - {match, binary:part(String, Start, Length), Submatches1}. - -regex_scan(Regex, String) -> - case re:run(String, Regex, [global]) of - {match, Captured} -> lists:map(fun(X) -> regex_matches(String, X) end, Captured); - nomatch -> [] - end. - -regex_replace(Regex, Subject, Replacement) -> - re:replace(Subject, Regex, Replacement, [global, {return, binary}]). - -base_decode64(S) -> - try {ok, base64:decode(S)} - catch error:_ -> {error, nil} - end. - -wrap_list(X) when is_list(X) -> X; -wrap_list(X) -> [X]. - -parse_query(Query) -> - case uri_string:dissect_query(Query) of - {error, _, _} -> {error, nil}; - Pairs -> - Pairs1 = lists:map(fun - ({K, true}) -> {K, <<"">>}; - (Pair) -> Pair - end, Pairs), - {ok, Pairs1} - end. - -percent_encode(B) -> percent_encode(B, <<>>). -percent_encode(<<>>, Acc) -> - Acc; -percent_encode(<>, Acc) -> - case percent_ok(H) of - true -> - percent_encode(T, <>); - false -> - <> = <>, - percent_encode(T, <>) - end. - -percent_decode(Cs) -> percent_decode(Cs, <<>>). -percent_decode(<<$%, C0, C1, Cs/binary>>, Acc) -> - case is_hex_digit(C0) andalso is_hex_digit(C1) of - true -> - B = ?HEX2DEC(C0)*16+?HEX2DEC(C1), - percent_decode(Cs, <>); - false -> - {error, nil} - end; -percent_decode(<>, Acc) -> - percent_decode(Cs, <>); -percent_decode(<<>>, Acc) -> - check_utf8(Acc). - -percent_ok($!) -> true; -percent_ok($$) -> true; -percent_ok($') -> true; -percent_ok($() -> true; -percent_ok($)) -> true; -percent_ok($*) -> true; -percent_ok($+) -> true; -percent_ok($-) -> true; -percent_ok($.) -> true; -percent_ok($_) -> true; -percent_ok($~) -> true; -percent_ok(C) when $0 =< C, C =< $9 -> true; -percent_ok(C) when $A =< C, C =< $Z -> true; -percent_ok(C) when $a =< C, C =< $z -> true; -percent_ok(_) -> false. - -is_hex_digit(C) -> - ($0 =< C andalso C =< $9) orelse ($a =< C andalso C =< $f) orelse ($A =< C andalso C =< $F). - -check_utf8(Cs) -> - case unicode:characters_to_list(Cs) of - {incomplete, _, _} -> {error, nil}; - {error, _, _} -> {error, nil}; - _ -> {ok, Cs} - end. - -uri_parse(String) -> - case uri_string:parse(String) of - {error, _, _} -> {error, nil}; - Uri -> - {ok, {uri, - maps_get_optional(Uri, scheme), - maps_get_optional(Uri, userinfo), - maps_get_optional(Uri, host), - maps_get_optional(Uri, port), - maps_get_or(Uri, path, <<>>), - maps_get_optional(Uri, query), - maps_get_optional(Uri, fragment) - }} - end. - -maps_get_optional(Map, Key) -> - try {some, maps:get(Key, Map)} - catch _:_ -> none - end. - -maps_get_or(Map, Key, Default) -> - try maps:get(Key, Map) - catch _:_ -> Default - end. - -print(String) -> - io:put_chars(String), - nil. - -println(String) -> - io:put_chars([String, $\n]), - nil. - -print_error(String) -> - io:put_chars(standard_error, String), - nil. - -println_error(String) -> - io:put_chars(standard_error, [String, $\n]), - nil. - -inspect(true) -> - "True"; -inspect(false) -> - "False"; -inspect(nil) -> - "Nil"; -inspect(Data) when is_map(Data) -> - Fields = [ - [<<"#(">>, inspect(Key), <<", ">>, inspect(Value), <<")">>] - || {Key, Value} <- maps:to_list(Data) - ], - ["dict.from_list([", lists:join(", ", Fields), "])"]; -inspect(Atom) when is_atom(Atom) -> - Binary = erlang:atom_to_binary(Atom), - case inspect_maybe_gleam_atom(Binary, none, <<>>) of - {ok, Inspected} -> Inspected; - {error, _} -> ["atom.create_from_string(\"", Binary, "\")"] - end; -inspect(Any) when is_integer(Any) -> - erlang:integer_to_list(Any); -inspect(Any) when is_float(Any) -> - io_lib_format:fwrite_g(Any); -inspect(Binary) when is_binary(Binary) -> - case inspect_maybe_utf8_string(Binary, <<>>) of - {ok, InspectedUtf8String} -> InspectedUtf8String; - {error, not_a_utf8_string} -> - Segments = [erlang:integer_to_list(X) || <> <= Binary], - ["<<", lists:join(", ", Segments), ">>"] - end; -inspect(Bits) when is_bitstring(Bits) -> - inspect_bit_array(Bits); -inspect(List) when is_list(List) -> - case inspect_list(List) of - {proper, Elements} -> ["[", Elements, "]"]; - {improper, Elements} -> ["//erl([", Elements, "])"] - end; -inspect(Any) when is_tuple(Any) % Record constructors - andalso is_atom(element(1, Any)) - andalso element(1, Any) =/= false - andalso element(1, Any) =/= true - andalso element(1, Any) =/= nil --> - [Atom | ArgsList] = erlang:tuple_to_list(Any), - Args = lists:join(<<", ">>, - lists:map(fun inspect/1, ArgsList) - ), - [inspect(Atom), "(", Args, ")"]; -inspect(Tuple) when is_tuple(Tuple) -> - Elements = lists:map(fun inspect/1, erlang:tuple_to_list(Tuple)), - ["#(", lists:join(", ", Elements), ")"]; -inspect(Any) when is_function(Any) -> - {arity, Arity} = erlang:fun_info(Any, arity), - ArgsAsciiCodes = lists:seq($a, $a + Arity - 1), - Args = lists:join(<<", ">>, - lists:map(fun(Arg) -> <> end, ArgsAsciiCodes) - ), - ["//fn(", Args, ") { ... }"]; -inspect(Any) -> - ["//erl(", io_lib:format("~p", [Any]), ")"]. - - -inspect_maybe_gleam_atom(<<>>, none, _) -> - {error, nil}; -inspect_maybe_gleam_atom(<>, none, _) when ?is_digit_char(First) -> - {error, nil}; -inspect_maybe_gleam_atom(<<"_", _Rest/binary>>, none, _) -> - {error, nil}; -inspect_maybe_gleam_atom(<<"_">>, _PrevChar, _Acc) -> - {error, nil}; -inspect_maybe_gleam_atom(<<"_", _Rest/binary>>, $_, _Acc) -> - {error, nil}; -inspect_maybe_gleam_atom(<>, _PrevChar, _Acc) - when not (?is_lowercase_char(First) orelse ?is_underscore_char(First) orelse ?is_digit_char(First)) -> - {error, nil}; -inspect_maybe_gleam_atom(<>, none, Acc) -> - inspect_maybe_gleam_atom(Rest, First, <>); -inspect_maybe_gleam_atom(<<"_", Rest/binary>>, _PrevChar, Acc) -> - inspect_maybe_gleam_atom(Rest, $_, Acc); -inspect_maybe_gleam_atom(<>, $_, Acc) -> - inspect_maybe_gleam_atom(Rest, First, <>); -inspect_maybe_gleam_atom(<>, _PrevChar, Acc) -> - inspect_maybe_gleam_atom(Rest, First, <>); -inspect_maybe_gleam_atom(<<>>, _PrevChar, Acc) -> - {ok, Acc}; -inspect_maybe_gleam_atom(A, B, C) -> - erlang:display({A, B, C}), - throw({gleam_error, A, B, C}). - -inspect_list([]) -> - {proper, []}; -inspect_list([First]) -> - {proper, [inspect(First)]}; -inspect_list([First | Rest]) when is_list(Rest) -> - {Kind, Inspected} = inspect_list(Rest), - {Kind, [inspect(First), <<", ">> | Inspected]}; -inspect_list([First | ImproperTail]) -> - {improper, [inspect(First), <<" | ">>, inspect(ImproperTail)]}. - -inspect_bit_array(Bits) -> - Text = inspect_bit_array(Bits, <<"<<">>), - <>">>. - -inspect_bit_array(<<>>, Acc) -> - Acc; -inspect_bit_array(<>, Acc) -> - inspect_bit_array(Rest, append_segment(Acc, erlang:integer_to_binary(X))); -inspect_bit_array(Rest, Acc) -> - Size = bit_size(Rest), - <> = Rest, - X1 = erlang:integer_to_binary(X), - Size1 = erlang:integer_to_binary(Size), - Segment = <>, - inspect_bit_array(<<>>, append_segment(Acc, Segment)). - -bit_array_to_int_and_size(A) -> - Size = bit_size(A), - <> = A, - {A1, Size}. - -append_segment(<<"<<">>, Segment) -> - <<"<<", Segment/binary>>; -append_segment(Acc, Segment) -> - <>. - - -inspect_maybe_utf8_string(Binary, Acc) -> - case Binary of - <<>> -> {ok, <<$", Acc/binary, $">>}; - <> -> - Escaped = case First of - $" -> <<$\\, $">>; - $\\ -> <<$\\, $\\>>; - $\r -> <<$\\, $r>>; - $\n -> <<$\\, $n>>; - $\t -> <<$\\, $t>>; - $\f -> <<$\\, $f>>; - X when X > 126, X < 160 -> convert_to_u(X); - X when X < 32 -> convert_to_u(X); - Other -> <> - end, - inspect_maybe_utf8_string(Rest, <>); - _ -> {error, not_a_utf8_string} - end. - -convert_to_u(Code) -> - list_to_binary(io_lib:format("\\u{~4.16.0B}", [Code])). - -float_to_string(Float) when is_float(Float) -> - erlang:iolist_to_binary(io_lib_format:fwrite_g(Float)). - -utf_codepoint_list_to_string(List) -> - case unicode:characters_to_binary(List) of - {error, _} -> erlang:error({gleam_error, {string_invalid_utf8, List}}); - Binary -> Binary - end. - -crop_string(String, Prefix) -> - case string:find(String, Prefix) of - nomatch -> String; - New -> New - end. - -contains_string(String, Substring) -> - is_bitstring(string:find(String, Substring)). - -base16_decode(String) -> - try - {ok, binary:decode_hex(String)} - catch - _:_ -> {error, nil} - end. - -string_replace(String, Pattern, Replacement) -> - string:replace(String, Pattern, Replacement, all). - -slice(String, Index, Length) -> - case string:slice(String, Index, Length) of - X when is_binary(X) -> X; - X when is_list(X) -> unicode:characters_to_binary(X) - end. diff --git a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam_stdlib.mjs b/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam_stdlib.mjs deleted file mode 100644 index 74df3d05952..00000000000 --- a/test-output/cases/echo_dict/build/packages/gleam_stdlib/src/gleam_stdlib.mjs +++ /dev/null @@ -1,992 +0,0 @@ -import { - BitArray, - Error, - List, - Ok, - Result, - UtfCodepoint, - stringBits, - toBitArray, - NonEmpty, - CustomType, -} from "./gleam.mjs"; -import { - CompileError as RegexCompileError, - Match as RegexMatch, -} from "./gleam/regex.mjs"; -import { DecodeError } from "./gleam/dynamic.mjs"; -import { Some, None } from "./gleam/option.mjs"; -import { Eq, Gt, Lt } from "./gleam/order.mjs"; -import Dict from "./dict.mjs"; - -const Nil = undefined; -const NOT_FOUND = {}; - -export function identity(x) { - return x; -} - -export function parse_int(value) { - if (/^[-+]?(\d+)$/.test(value)) { - return new Ok(parseInt(value)); - } else { - return new Error(Nil); - } -} - -export function parse_float(value) { - if (/^[-+]?(\d+)\.(\d+)([eE][-+]?\d+)?$/.test(value)) { - return new Ok(parseFloat(value)); - } else { - return new Error(Nil); - } -} - -export function to_string(term) { - return term.toString(); -} - -export function float_to_string(float) { - const string = float.toString().replace('+', ''); - if (string.indexOf(".") >= 0) { - return string; - } else { - const index = string.indexOf("e"); - if (index >= 0) { - return string.slice(0, index) + '.0' + string.slice(index); - } else { - return string + ".0"; - } - } -} - -export function int_to_base_string(int, base) { - return int.toString(base).toUpperCase(); -} - -const int_base_patterns = { - 2: /[^0-1]/, - 3: /[^0-2]/, - 4: /[^0-3]/, - 5: /[^0-4]/, - 6: /[^0-5]/, - 7: /[^0-6]/, - 8: /[^0-7]/, - 9: /[^0-8]/, - 10: /[^0-9]/, - 11: /[^0-9a]/, - 12: /[^0-9a-b]/, - 13: /[^0-9a-c]/, - 14: /[^0-9a-d]/, - 15: /[^0-9a-e]/, - 16: /[^0-9a-f]/, - 17: /[^0-9a-g]/, - 18: /[^0-9a-h]/, - 19: /[^0-9a-i]/, - 20: /[^0-9a-j]/, - 21: /[^0-9a-k]/, - 22: /[^0-9a-l]/, - 23: /[^0-9a-m]/, - 24: /[^0-9a-n]/, - 25: /[^0-9a-o]/, - 26: /[^0-9a-p]/, - 27: /[^0-9a-q]/, - 28: /[^0-9a-r]/, - 29: /[^0-9a-s]/, - 30: /[^0-9a-t]/, - 31: /[^0-9a-u]/, - 32: /[^0-9a-v]/, - 33: /[^0-9a-w]/, - 34: /[^0-9a-x]/, - 35: /[^0-9a-y]/, - 36: /[^0-9a-z]/, -}; - -export function int_from_base_string(string, base) { - if (int_base_patterns[base].test(string.replace(/^-/, "").toLowerCase())) { - return new Error(Nil); - } - - const result = parseInt(string, base); - - if (isNaN(result)) { - return new Error(Nil); - } - - return new Ok(result); -} - -export function string_replace(string, target, substitute) { - if (typeof string.replaceAll !== "undefined") { - return string.replaceAll(target, substitute); - } - // Fallback for older Node.js versions: - // 1. - // 2. - // TODO: This fallback could be remove once Node.js 14 is EOL - // aka on or after 2024-04-30 - return string.replace( - // $& means the whole matched string - new RegExp(target.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g"), - substitute, - ); -} - -export function string_reverse(string) { - return [...string].reverse().join(""); -} - -export function string_length(string) { - if (string === "") { - return 0; - } - const iterator = graphemes_iterator(string); - if (iterator) { - let i = 0; - for (const _ of iterator) { - i++; - } - return i; - } else { - return string.match(/./gsu).length; - } -} - -export function graphemes(string) { - const iterator = graphemes_iterator(string); - if (iterator) { - return List.fromArray(Array.from(iterator).map((item) => item.segment)); - } else { - return List.fromArray(string.match(/./gsu)); - } -} - -let segmenter = undefined; - -function graphemes_iterator(string) { - if (globalThis.Intl && Intl.Segmenter) { - segmenter ||= new Intl.Segmenter(); - return segmenter.segment(string)[Symbol.iterator](); - } -} - -export function pop_grapheme(string) { - let first; - const iterator = graphemes_iterator(string); - if (iterator) { - first = iterator.next().value?.segment; - } else { - first = string.match(/./su)?.[0]; - } - if (first) { - return new Ok([first, string.slice(first.length)]); - } else { - return new Error(Nil); - } -} - -export function lowercase(string) { - return string.toLowerCase(); -} - -export function uppercase(string) { - return string.toUpperCase(); -} - -export function less_than(a, b) { - return a < b; -} - -export function add(a, b) { - return a + b; -} - -export function split(xs, pattern) { - return List.fromArray(xs.split(pattern)); -} - -export function join(xs, separator) { - const iterator = xs[Symbol.iterator](); - let result = iterator.next().value || ""; - let current = iterator.next(); - while (!current.done) { - result = result + separator + current.value; - current = iterator.next(); - } - return result; -} - -export function concat(xs) { - let result = ""; - for (const x of xs) { - result = result + x; - } - return result; -} - -export function length(data) { - return data.length; -} - -export function string_slice(string, idx, len) { - if (len <= 0 || idx >= string.length) { - return ""; - } - - const iterator = graphemes_iterator(string); - if (iterator) { - while (idx-- > 0) { - iterator.next(); - } - - let result = ""; - - while (len-- > 0) { - const v = iterator.next().value; - if (v === undefined) { - break; - } - - result += v.segment; - } - - return result; - } else { - return string.match(/./gsu).slice(idx, idx + len).join(""); - } -} - -export function crop_string(string, substring) { - return string.substring(string.indexOf(substring)); -} - -export function contains_string(haystack, needle) { - return haystack.indexOf(needle) >= 0; -} - -export function starts_with(haystack, needle) { - return haystack.startsWith(needle); -} - -export function ends_with(haystack, needle) { - return haystack.endsWith(needle); -} - -export function split_once(haystack, needle) { - const index = haystack.indexOf(needle); - if (index >= 0) { - const before = haystack.slice(0, index); - const after = haystack.slice(index + needle.length); - return new Ok([before, after]); - } else { - return new Error(Nil); - } -} - -const unicode_whitespaces = [ - "\u0020", // Space - "\u0009", // Horizontal tab - "\u000A", // Line feed - "\u000B", // Vertical tab - "\u000C", // Form feed - "\u000D", // Carriage return - "\u0085", // Next line - "\u2028", // Line separator - "\u2029", // Paragraph separator -].join(""); - -const left_trim_regex = new RegExp(`^([${unicode_whitespaces}]*)`, "g"); -const right_trim_regex = new RegExp(`([${unicode_whitespaces}]*)$`, "g"); - -export function trim(string) { - return trim_left(trim_right(string)); -} - -export function trim_left(string) { - return string.replace(left_trim_regex, ""); -} - -export function trim_right(string) { - return string.replace(right_trim_regex, ""); -} - -export function bit_array_from_string(string) { - return toBitArray([stringBits(string)]); -} - -export function bit_array_concat(bit_arrays) { - return toBitArray(bit_arrays.toArray().map((b) => b.buffer)); -} - -export function console_log(term) { - console.log(term); -} - -export function console_error(term) { - console.error(term); -} - -export function crash(message) { - throw new globalThis.Error(message); -} - -export function bit_array_to_string(bit_array) { - try { - const decoder = new TextDecoder("utf-8", { fatal: true }); - return new Ok(decoder.decode(bit_array.buffer)); - } catch { - return new Error(Nil); - } -} - -export function print(string) { - if (typeof process === "object") { - process.stdout.write(string); // We can write without a trailing newline - } else if (typeof Deno === "object") { - Deno.stdout.writeSync(new TextEncoder().encode(string)); // We can write without a trailing newline - } else { - console.log(string); // We're in a browser. Newlines are mandated - } -} - -export function print_error(string) { - if (typeof process === "object" && process.stderr?.write) { - process.stderr.write(string); // We can write without a trailing newline - } else if (typeof Deno === "object") { - Deno.stderr.writeSync(new TextEncoder().encode(string)); // We can write without a trailing newline - } else { - console.error(string); // We're in a browser. Newlines are mandated - } -} - -export function print_debug(string) { - if (typeof process === "object" && process.stderr?.write) { - process.stderr.write(string + "\n"); // If we're in Node.js, use `stderr` - } else if (typeof Deno === "object") { - Deno.stderr.writeSync(new TextEncoder().encode(string + "\n")); // If we're in Deno, use `stderr` - } else { - console.log(string); // Otherwise, use `console.log` (so that it doesn't look like an error) - } -} - -export function ceiling(float) { - return Math.ceil(float); -} - -export function floor(float) { - return Math.floor(float); -} - -export function round(float) { - return Math.round(float); -} - -export function truncate(float) { - return Math.trunc(float); -} - -export function power(base, exponent) { - // It is checked in Gleam that: - // - The base is non-negative and that the exponent is not fractional. - // - The base is non-zero and the exponent is non-negative (otherwise - // the result will essentially be division by zero). - // It can thus be assumed that valid input is passed to the Math.pow - // function and a NaN or Infinity value will not be produced. - return Math.pow(base, exponent); -} - -export function random_uniform() { - const random_uniform_result = Math.random(); - // With round-to-nearest-even behavior, the ranges claimed for the functions below - // (excluding the one for Math.random() itself) aren't exact. - // If extremely large bounds are chosen (2^53 or higher), - // it's possible in extremely rare cases to calculate the usually-excluded upper bound. - // Note that as numbers in JavaScript are IEEE 754 floating point numbers - // See: - // Because of this, we just loop 'until' we get a valid result where 0.0 <= x < 1.0: - if (random_uniform_result === 1.0) { - return random_uniform(); - } - return random_uniform_result; -} - -export function bit_array_slice(bits, position, length) { - const start = Math.min(position, position + length); - const end = Math.max(position, position + length); - if (start < 0 || end > bits.length) return new Error(Nil); - const byteOffset = bits.buffer.byteOffset + start; - const buffer = new Uint8Array( - bits.buffer.buffer, - byteOffset, - Math.abs(length), - ); - return new Ok(new BitArray(buffer)); -} - -export function codepoint(int) { - return new UtfCodepoint(int); -} - -export function string_to_codepoint_integer_list(string) { - return List.fromArray(Array.from(string).map((item) => item.codePointAt(0))); -} - -export function utf_codepoint_list_to_string(utf_codepoint_integer_list) { - return utf_codepoint_integer_list - .toArray() - .map((x) => String.fromCodePoint(x.value)) - .join(""); -} - -export function utf_codepoint_to_int(utf_codepoint) { - return utf_codepoint.value; -} - -export function regex_check(regex, string) { - regex.lastIndex = 0; - return regex.test(string); -} - -export function compile_regex(pattern, options) { - try { - let flags = "gu"; - if (options.case_insensitive) flags += "i"; - if (options.multi_line) flags += "m"; - return new Ok(new RegExp(pattern, flags)); - } catch (error) { - const number = (error.columnNumber || 0) | 0; - return new Error(new RegexCompileError(error.message, number)); - } -} - -export function regex_split(regex, string) { - return List.fromArray( - string.split(regex).map((item) => (item === undefined ? "" : item)), - ); -} - -export function regex_scan(regex, string) { - const matches = Array.from(string.matchAll(regex)).map((match) => { - const content = match[0]; - const submatches = []; - for (let n = match.length - 1; n > 0; n--) { - if (match[n]) { - submatches[n - 1] = new Some(match[n]); - continue; - } - if (submatches.length > 0) { - submatches[n - 1] = new None(); - } - } - return new RegexMatch(content, List.fromArray(submatches)); - }); - return List.fromArray(matches); -} - -export function regex_replace(regex, original_string, replacement) { - return original_string.replaceAll(regex, replacement); -} - -export function new_map() { - return Dict.new(); -} - -export function map_size(map) { - return map.size; -} - -export function map_to_list(map) { - return List.fromArray(map.entries()); -} - -export function map_remove(key, map) { - return map.delete(key); -} - -export function map_get(map, key) { - const value = map.get(key, NOT_FOUND); - if (value === NOT_FOUND) { - return new Error(Nil); - } - return new Ok(value); -} - -export function map_insert(key, value, map) { - return map.set(key, value); -} - -function unsafe_percent_decode(string) { - return decodeURIComponent(string || ""); -} - -function unsafe_percent_decode_query(string) { - return decodeURIComponent((string || "").replace("+", " ")); -} - -export function percent_decode(string) { - try { - return new Ok(unsafe_percent_decode(string)); - } catch { - return new Error(Nil); - } -} - -export function percent_encode(string) { - return encodeURIComponent(string).replace("%2B", "+"); -} - -export function parse_query(query) { - try { - const pairs = []; - for (const section of query.split("&")) { - const [key, value] = section.split("="); - if (!key) continue; - - const decodedKey = unsafe_percent_decode_query(key); - const decodedValue = unsafe_percent_decode_query(value); - pairs.push([decodedKey, decodedValue]); - } - return new Ok(List.fromArray(pairs)); - } catch { - return new Error(Nil); - } -} - -const b64EncodeLookup = [ - 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, - 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, - 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, - 122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43, 47, -]; - -let b64TextDecoder; - -// Implementation based on https://github.com/mitschabaude/fast-base64/blob/main/js.js -export function encode64(bit_array, padding) { - b64TextDecoder ??= new TextDecoder(); - - const bytes = bit_array.buffer; - - const m = bytes.length; - const k = m % 3; - const n = Math.floor(m / 3) * 4 + (k && k + 1); - const N = Math.ceil(m / 3) * 4; - const encoded = new Uint8Array(N); - - for (let i = 0, j = 0; j < m; i += 4, j += 3) { - const y = (bytes[j] << 16) + (bytes[j + 1] << 8) + (bytes[j + 2] | 0); - encoded[i] = b64EncodeLookup[y >> 18]; - encoded[i + 1] = b64EncodeLookup[(y >> 12) & 0x3f]; - encoded[i + 2] = b64EncodeLookup[(y >> 6) & 0x3f]; - encoded[i + 3] = b64EncodeLookup[y & 0x3f]; - } - - let base64 = b64TextDecoder.decode(new Uint8Array(encoded.buffer, 0, n)); - - if (padding) { - if (k === 1) { - base64 += "=="; - } else if (k === 2) { - base64 += "="; - } - } - - return base64; -} - -// From https://developer.mozilla.org/en-US/docs/Glossary/Base64 -export function decode64(sBase64) { - try { - const binString = atob(sBase64); - const length = binString.length; - const array = new Uint8Array(length); - for (let i = 0; i < length; i++) { - array[i] = binString.charCodeAt(i); - } - return new Ok(new BitArray(array)); - } catch { - return new Error(Nil); - } -} - -export function classify_dynamic(data) { - if (typeof data === "string") { - return "String"; - } else if (typeof data === "boolean") { - return "Bool"; - } else if (data instanceof Result) { - return "Result"; - } else if (data instanceof List) { - return "List"; - } else if (data instanceof BitArray) { - return "BitArray"; - } else if (data instanceof Dict) { - return "Dict"; - } else if (Number.isInteger(data)) { - return "Int"; - } else if (Array.isArray(data)) { - return `Tuple of ${data.length} elements`; - } else if (typeof data === "number") { - return "Float"; - } else if (data === null) { - return "Null"; - } else if (data === undefined) { - return "Nil"; - } else { - const type = typeof data; - return type.charAt(0).toUpperCase() + type.slice(1); - } -} - -function decoder_error(expected, got) { - return decoder_error_no_classify(expected, classify_dynamic(got)); -} - -function decoder_error_no_classify(expected, got) { - return new Error( - List.fromArray([new DecodeError(expected, got, List.fromArray([]))]), - ); -} - -export function decode_string(data) { - return typeof data === "string" - ? new Ok(data) - : decoder_error("String", data); -} - -export function decode_int(data) { - return Number.isInteger(data) ? new Ok(data) : decoder_error("Int", data); -} - -export function decode_float(data) { - return typeof data === "number" ? new Ok(data) : decoder_error("Float", data); -} - -export function decode_bool(data) { - return typeof data === "boolean" ? new Ok(data) : decoder_error("Bool", data); -} - -export function decode_bit_array(data) { - if (data instanceof BitArray) { - return new Ok(data); - } - if (data instanceof Uint8Array) { - return new Ok(new BitArray(data)); - } - return decoder_error("BitArray", data); -} - -export function decode_tuple(data) { - return Array.isArray(data) ? new Ok(data) : decoder_error("Tuple", data); -} - -export function decode_tuple2(data) { - return decode_tupleN(data, 2); -} - -export function decode_tuple3(data) { - return decode_tupleN(data, 3); -} - -export function decode_tuple4(data) { - return decode_tupleN(data, 4); -} - -export function decode_tuple5(data) { - return decode_tupleN(data, 5); -} - -export function decode_tuple6(data) { - return decode_tupleN(data, 6); -} - -function decode_tupleN(data, n) { - if (Array.isArray(data) && data.length == n) { - return new Ok(data); - } - - const list = decode_exact_length_list(data, n); - if (list) return new Ok(list); - - return decoder_error(`Tuple of ${n} elements`, data); -} - -function decode_exact_length_list(data, n) { - if (!(data instanceof List)) return; - - const elements = []; - let current = data; - - for (let i = 0; i < n; i++) { - if (!(current instanceof NonEmpty)) break; - elements.push(current.head); - current = current.tail; - } - - if (elements.length === n && !(current instanceof NonEmpty)) return elements; -} - -export function tuple_get(data, index) { - return index >= 0 && data.length > index - ? new Ok(data[index]) - : new Error(Nil); -} - -export function decode_list(data) { - if (Array.isArray(data)) { - return new Ok(List.fromArray(data)); - } - return data instanceof List ? new Ok(data) : decoder_error("List", data); -} - -export function decode_result(data) { - return data instanceof Result ? new Ok(data) : decoder_error("Result", data); -} - -export function decode_map(data) { - if (data instanceof Dict) { - return new Ok(data); - } - if (data instanceof Map || data instanceof WeakMap) { - return new Ok(Dict.fromMap(data)); - } - if (data == null) { - return decoder_error("Dict", data); - } - if (typeof data !== "object") { - return decoder_error("Dict", data); - } - const proto = Object.getPrototypeOf(data); - if (proto === Object.prototype || proto === null) { - return new Ok(Dict.fromObject(data)); - } - return decoder_error("Dict", data); -} - -export function decode_option(data, decoder) { - if (data === null || data === undefined || data instanceof None) - return new Ok(new None()); - if (data instanceof Some) data = data[0]; - const result = decoder(data); - if (result.isOk()) { - return new Ok(new Some(result[0])); - } else { - return result; - } -} - -export function decode_field(value, name) { - const not_a_map_error = () => decoder_error("Dict", value); - - if ( - value instanceof Dict || - value instanceof WeakMap || - value instanceof Map - ) { - const entry = map_get(value, name); - return new Ok(entry.isOk() ? new Some(entry[0]) : new None()); - } else if (value === null) { - return not_a_map_error(); - } else if (Object.getPrototypeOf(value) == Object.prototype) { - return try_get_field(value, name, () => new Ok(new None())); - } else { - return try_get_field(value, name, not_a_map_error); - } -} - -function try_get_field(value, field, or_else) { - try { - return field in value ? new Ok(new Some(value[field])) : or_else(); - } catch { - return or_else(); - } -} - -export function byte_size(string) { - return new TextEncoder().encode(string).length; -} - -// In Javascript bitwise operations convert numbers to a sequence of 32 bits -// while Erlang uses arbitrary precision. -// To get around this problem and get consistent results use BigInt and then -// downcast the value back to a Number value. - -export function bitwise_and(x, y) { - return Number(BigInt(x) & BigInt(y)); -} - -export function bitwise_not(x) { - return Number(~BigInt(x)); -} - -export function bitwise_or(x, y) { - return Number(BigInt(x) | BigInt(y)); -} - -export function bitwise_exclusive_or(x, y) { - return Number(BigInt(x) ^ BigInt(y)); -} - -export function bitwise_shift_left(x, y) { - return Number(BigInt(x) << BigInt(y)); -} - -export function bitwise_shift_right(x, y) { - return Number(BigInt(x) >> BigInt(y)); -} - -export function inspect(v) { - const t = typeof v; - if (v === true) return "True"; - if (v === false) return "False"; - if (v === null) return "//js(null)"; - if (v === undefined) return "Nil"; - if (t === "string") return inspectString(v); - if (t === "bigint" || Number.isInteger(v)) return v.toString(); - if (t === "number") return float_to_string(v); - if (Array.isArray(v)) return `#(${v.map(inspect).join(", ")})`; - if (v instanceof List) return inspectList(v); - if (v instanceof UtfCodepoint) return inspectUtfCodepoint(v); - if (v instanceof BitArray) return inspectBitArray(v); - if (v instanceof CustomType) return inspectCustomType(v); - if (v instanceof Dict) return inspectDict(v); - if (v instanceof Set) return `//js(Set(${[...v].map(inspect).join(", ")}))`; - if (v instanceof RegExp) return `//js(${v})`; - if (v instanceof Date) return `//js(Date("${v.toISOString()}"))`; - if (v instanceof Function) { - const args = []; - for (const i of Array(v.length).keys()) - args.push(String.fromCharCode(i + 97)); - return `//fn(${args.join(", ")}) { ... }`; - } - return inspectObject(v); -} - -function inspectString(str) { - let new_str = '"'; - for (let i = 0; i < str.length; i++) { - let char = str[i]; - switch (char) { - case "\n": - new_str += "\\n"; - break; - case "\r": - new_str += "\\r"; - break; - case "\t": - new_str += "\\t"; - break; - case "\f": - new_str += "\\f"; - break; - case "\\": - new_str += "\\\\"; - break; - case '"': - new_str += '\\"'; - break; - default: - if (char < " " || (char > "~" && char < "\u{00A0}")) { - new_str += - "\\u{" + - char.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0") + - "}"; - } else { - new_str += char; - } - } - } - new_str += '"'; - return new_str; -} - -function inspectDict(map) { - let body = "dict.from_list(["; - let first = true; - map.forEach((value, key) => { - if (!first) body = body + ", "; - body = body + "#(" + inspect(key) + ", " + inspect(value) + ")"; - first = false; - }); - return body + "])"; -} - -function inspectObject(v) { - const name = Object.getPrototypeOf(v)?.constructor?.name || "Object"; - const props = []; - for (const k of Object.keys(v)) { - props.push(`${inspect(k)}: ${inspect(v[k])}`); - } - const body = props.length ? " " + props.join(", ") + " " : ""; - const head = name === "Object" ? "" : name + " "; - return `//js(${head}{${body}})`; -} - -function inspectCustomType(record) { - const props = Object.keys(record) - .map((label) => { - const value = inspect(record[label]); - return isNaN(parseInt(label)) ? `${label}: ${value}` : value; - }) - .join(", "); - return props - ? `${record.constructor.name}(${props})` - : record.constructor.name; -} - -export function inspectList(list) { - return `[${list.toArray().map(inspect).join(", ")}]`; -} - -export function inspectBitArray(bits) { - return `<<${Array.from(bits.buffer).join(", ")}>>`; -} - -export function inspectUtfCodepoint(codepoint) { - return `//utfcodepoint(${String.fromCodePoint(codepoint.value)})`; -} - -export function base16_encode(bit_array) { - let result = ""; - for (const byte of bit_array.buffer) { - result += byte.toString(16).padStart(2, "0").toUpperCase(); - } - return result; -} - -export function base16_decode(string) { - const bytes = new Uint8Array(string.length / 2); - for (let i = 0; i < string.length; i += 2) { - const a = parseInt(string[i], 16); - const b = parseInt(string[i + 1], 16); - if (isNaN(a) || isNaN(b)) return new Error(Nil); - bytes[i / 2] = a * 16 + b; - } - return new Ok(new BitArray(bytes)); -} - -export function bit_array_inspect(bits, acc) { - return `${acc}${[...bits.buffer].join(", ")}`; -} - -export function bit_array_compare(first, second) { - for (let i = 0; i < first.length; i++) { - if (i >= second.length) { - return new Gt(); // first has more items - } - const f = first.buffer[i]; - const s = second.buffer[i]; - if (f > s) { - return new Gt(); - } - if (f < s) { - return new Lt(); - } - } - // This means that either first did not have any items - // or all items in first were equal to second. - if (first.length === second.length) { - return new Eq(); - } - return new Lt(); // second has more items -} diff --git a/test-output/cases/echo_dict/build/packages/packages.toml b/test-output/cases/echo_dict/build/packages/packages.toml deleted file mode 100644 index ceabd44c1f1..00000000000 --- a/test-output/cases/echo_dict/build/packages/packages.toml +++ /dev/null @@ -1,2 +0,0 @@ -[packages] -gleam_stdlib = "0.41.0" diff --git a/test-output/cases/echo_dict/manifest.toml b/test-output/cases/echo_dict/manifest.toml deleted file mode 100644 index 7b033305371..00000000000 --- a/test-output/cases/echo_dict/manifest.toml +++ /dev/null @@ -1,9 +0,0 @@ -# This file was generated by Gleam -# You typically do not need to edit this file - -packages = [ - { name = "gleam_stdlib", version = "0.41.0", build_tools = ["gleam"], requirements = [], otp_app = "gleam_stdlib", source = "hex", outer_checksum = "1B2F80CB1B66B027E3198A2FF71EF3F2F31DF89ED97AD606F25FD387A4C3C1EF" }, -] - -[requirements] -gleam_stdlib = { version = ">= 0.34.0 and < 2.0.0" } diff --git a/test-output/cases/echo_float/build/dev/erlang/echo_float/_gleam_artefacts/echo_float@@main.erl b/test-output/cases/echo_float/build/dev/erlang/echo_float/_gleam_artefacts/echo_float@@main.erl deleted file mode 100644 index b66bb86d680..00000000000 --- a/test-output/cases/echo_float/build/dev/erlang/echo_float/_gleam_artefacts/echo_float@@main.erl +++ /dev/null @@ -1,99 +0,0 @@ --module('echo_float@@main'). --export([run/1]). - --define(red, "\e[31;1m"). --define(grey, "\e[90m"). --define(reset_color, "\e[39m"). --define(reset_all, "\e[0m"). - -run(Module) -> - io:setopts(standard_io, [binary, {encoding, utf8}]), - io:setopts(standard_error, [{encoding, utf8}]), - process_flag(trap_exit, true), - Pid = spawn_link(fun() -> run_module(Module) end), - receive - {'EXIT', Pid, {Reason, StackTrace}} -> - print_error(exit, Reason, StackTrace), - init:stop(1) - end. - -run_module(Module) -> - try - {ok, _} = application:ensure_all_started('echo_float'), - erlang:process_flag(trap_exit, false), - Module:main(), - erlang:halt(0) - catch - Class:Reason:StackTrace -> - print_error(Class, Reason, StackTrace), - init:stop(1) - end. - -print_error(Class, Error, Stacktrace) -> - Printed = [ - ?red, "runtime error", ?reset_color, ": ", error_class(Class, Error), ?reset_all, - "\n\n", - error_message(Error), - "\n\n", - error_details(Class, Error), - "stacktrace:\n", - [error_frame(Line) || Line <- refine_first(Error, Stacktrace)] - ], - io:format(standard_error, "~ts~n", [Printed]). - -refine_first(#{gleam_error := _, line := L}, [{M, F, A, [{file, Fi} | _]} | S]) -> - [{M, F, A, [{file, Fi}, {line, L}]} | S]; -refine_first(_, S) -> - S. - -error_class(_, #{gleam_error := panic}) -> "panic"; -error_class(_, #{gleam_error := todo}) -> "todo"; -error_class(_, #{gleam_error := let_assert}) -> "let assert"; -error_class(Class, _) -> ["Erlang ", atom_to_binary(Class)]. - -error_message(#{gleam_error := _, message := M}) -> - M; -error_message(undef) -> - <<"A function was called but it did not exist."/utf8 >>; -error_message({case_clause, _}) -> - <<"No pattern matched in an Erlang case expression."/utf8>>; -error_message({badmatch, _}) -> - <<"An Erlang assignment pattern did not match."/utf8>>; -error_message(function_clause) -> - <<"No Erlang function clause matched the arguments it was called with."/utf8>>; -error_message(_) -> - <<"An error occurred outside of Gleam."/utf8>>. - -error_details(_, #{gleam_error := let_assert, value := V}) -> - ["unmatched value:\n ", print_term(V), $\n, $\n]; -error_details(_, {case_clause, V}) -> - ["unmatched value:\n ", print_term(V), $\n, $\n]; -error_details(_, {badmatch, V}) -> - ["unmatched value:\n ", print_term(V), $\n, $\n]; -error_details(_, #{gleam_error := _}) -> - []; -error_details(error, function_clause) -> - []; -error_details(error, undef) -> - []; -error_details(C, E) -> - ["erlang:", atom_to_binary(C), $(, print_term(E), $), $\n, $\n]. - -print_term(T) -> - try - gleam@string:inspect(T) - catch - _:_ -> io_lib:format("~p", [T]) - end. - -error_frame({?MODULE, _, _, _}) -> []; -error_frame({erl_eval, _, _, _}) -> []; -error_frame({init, _, _, _}) -> []; -error_frame({M, F, _, O}) -> - M1 = string:replace(atom_to_binary(M), "@", "/", all), - [" ", M1, $., atom_to_binary(F), error_frame_end(O), $\n]. - -error_frame_end([{file, Fi}, {line, L} | _]) -> - [?grey, $\s, Fi, $:, integer_to_binary(L), ?reset_all]; -error_frame_end(_) -> - [?grey, " unknown source", ?reset_all]. \ No newline at end of file diff --git a/test-output/cases/echo_float/build/dev/erlang/echo_float/_gleam_artefacts/gleam@@compile.erl b/test-output/cases/echo_float/build/dev/erlang/echo_float/_gleam_artefacts/gleam@@compile.erl deleted file mode 100644 index 3e0a645b737..00000000000 --- a/test-output/cases/echo_float/build/dev/erlang/echo_float/_gleam_artefacts/gleam@@compile.erl +++ /dev/null @@ -1,163 +0,0 @@ -#!/usr/bin/env escript --mode(compile). - -% TODO: Don't concurrently print warnings and errors -% TODO: Some tests - -main(_) -> compile_package_loop(). - -compile_package_loop() -> - case file:read_line(standard_io) of - eof -> ok; - {ok, Line} -> - Chars = unicode:characters_to_list(Line), - {ok, Tokens, _} = erl_scan:string(Chars), - {ok, {Lib, Out, Modules}} = erl_parse:parse_term(Tokens), - case compile_package(Lib, Out, Modules) of - ok -> io:put_chars("gleam-compile-result-ok\n"); - err -> io:put_chars("gleam-compile-result-error\n") - end, - compile_package_loop() - end. - -compile_package(Lib, Out, Modules) -> - IsElixirModule = fun(Module) -> - filename:extension(Module) =:= ".ex" - end, - {ElixirModules, ErlangModules} = lists:partition(IsElixirModule, Modules), - ok = configure_logging(), - ok = add_lib_to_erlang_path(Lib), - ok = filelib:ensure_dir([Out, $/]), - {ErlangOk, _ErlangBeams} = compile_erlang(ErlangModules, Out), - {ElixirOk, _ElixirBeams} = case ErlangOk of - true -> compile_elixir(ElixirModules, Out); - false -> {false, []} - end, - ok = del_lib_from_erlang_path(Lib), - case ErlangOk and ElixirOk of - true -> ok; - false -> err - end. - -compile_erlang(Modules, Out) -> - Workers = start_compiler_workers(Out), - ok = producer_loop(Modules, Workers), - collect_results({true, []}). - -collect_results(Acc = {Result, Beams}) -> - receive - {compiled, Beam} -> collect_results({Result, [Beam | Beams]}); - failed -> collect_results({false, Beams}) - after 0 -> Acc - end. - -producer_loop([], 0) -> - ok; -producer_loop([], Workers) -> - receive - {work_please, _} -> producer_loop([], Workers - 1) - end; -producer_loop([Module | Modules], Workers) -> - receive - {work_please, Worker} -> - erlang:send(Worker, {module, Module}), - producer_loop(Modules, Workers) - end. - -start_compiler_workers(Out) -> - Parent = self(), - NumSchedulers = erlang:system_info(schedulers), - SpawnWorker = fun(_) -> - erlang:spawn_link(fun() -> worker_loop(Parent, Out) end) - end, - lists:foreach(SpawnWorker, lists:seq(1, NumSchedulers)), - NumSchedulers. - -worker_loop(Parent, Out) -> - Options = [report_errors, report_warnings, debug_info, {outdir, Out}], - erlang:send(Parent, {work_please, self()}), - receive - {module, Module} -> - log({compiling, Module}), - case compile:file(Module, Options) of - {ok, ModuleName} -> - Beam = filename:join(Out, ModuleName) ++ ".beam", - Message = {compiled, Beam}, - log(Message), - erlang:send(Parent, Message); - error -> - log({failed, Module}), - erlang:send(Parent, failed) - end, - worker_loop(Parent, Out) - end. - -compile_elixir(Modules, Out) -> - Error = [ - "The program elixir was not found. Is it installed?", - $\n, - "Documentation for installing Elixir can be viewed here:", - $\n, - "https://elixir-lang.org/install.html" - ], - case Modules of - [] -> {true, []}; - _ -> - log({starting, "compiler.app"}), - ok = application:start(compiler), - log({starting, "elixir.app"}), - case application:start(elixir) of - ok -> do_compile_elixir(Modules, Out); - _ -> - io:put_chars(standard_error, [Error, $\n]), - {false, []} - end - end. - -do_compile_elixir(Modules, Out) -> - ModuleBins = lists:map(fun(Module) -> - log({compiling, Module}), - list_to_binary(Module) - end, Modules), - OutBin = list_to_binary(Out), - Options = [{dest, OutBin}], - % Silence "redefining module" warnings. - % Compiled modules in the build directory are added to the code path. - % These warnings result from recompiling loaded modules. - % TODO: This line can likely be removed if/when the build directory is cleaned before every compilation. - 'Elixir.Code':compiler_options([{ignore_module_conflict, true}]), - case 'Elixir.Kernel.ParallelCompiler':compile_to_path(ModuleBins, OutBin, Options) of - {ok, ModuleAtoms, _} -> - ToBeam = fun(ModuleAtom) -> - Beam = filename:join(Out, atom_to_list(ModuleAtom)) ++ ".beam", - log({compiled, Beam}), - Beam - end, - {true, lists:map(ToBeam, ModuleAtoms)}; - {error, Errors, _} -> - % Log all filenames associated with modules that failed to compile. - % Note: The compiler prints compilation errors upon encountering them. - ErrorFiles = lists:usort([File || {File, _, _} <- Errors]), - Log = fun(File) -> - log({failed, binary_to_list(File)}) - end, - lists:foreach(Log, ErrorFiles), - {false, []}; - _ -> {false, []} - end. - -add_lib_to_erlang_path(Lib) -> - code:add_paths(filelib:wildcard([Lib, "/*/ebin"])). - -del_lib_from_erlang_path(Lib) -> - code:del_paths(filelib:wildcard([Lib, "/*/ebin"])). - -configure_logging() -> - Enabled = os:getenv("GLEAM_LOG") /= false, - persistent_term:put(gleam_logging_enabled, Enabled). - -log(Term) -> - case persistent_term:get(gleam_logging_enabled) of - true -> erlang:display(Term), ok; - false -> ok - end. diff --git a/test-output/cases/echo_float/build/dev/erlang/echo_float/_gleam_artefacts/main.cache b/test-output/cases/echo_float/build/dev/erlang/echo_float/_gleam_artefacts/main.cache deleted file mode 100644 index 1e236b2014b..00000000000 Binary files a/test-output/cases/echo_float/build/dev/erlang/echo_float/_gleam_artefacts/main.cache and /dev/null differ diff --git a/test-output/cases/echo_float/build/dev/erlang/echo_float/_gleam_artefacts/main.cache_meta b/test-output/cases/echo_float/build/dev/erlang/echo_float/_gleam_artefacts/main.cache_meta deleted file mode 100644 index 60b0815764f..00000000000 Binary files a/test-output/cases/echo_float/build/dev/erlang/echo_float/_gleam_artefacts/main.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_float/build/dev/erlang/echo_float/_gleam_artefacts/main.cache_warnings b/test-output/cases/echo_float/build/dev/erlang/echo_float/_gleam_artefacts/main.cache_warnings deleted file mode 100644 index 1b1cb4d44c5..00000000000 Binary files a/test-output/cases/echo_float/build/dev/erlang/echo_float/_gleam_artefacts/main.cache_warnings and /dev/null differ diff --git a/test-output/cases/echo_float/build/dev/erlang/echo_float/_gleam_artefacts/main.erl b/test-output/cases/echo_float/build/dev/erlang/echo_float/_gleam_artefacts/main.erl deleted file mode 100644 index e003fa63b7a..00000000000 --- a/test-output/cases/echo_float/build/dev/erlang/echo_float/_gleam_artefacts/main.erl +++ /dev/null @@ -1,191 +0,0 @@ --module(main). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([main/0]). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_float/src/main.gleam", 1). --spec main() -> float(). -main() -> - echo(1.0, "src/main.gleam", 2), - echo(2.1, "src/main.gleam", 3), - echo(11.11, "src/main.gleam", 4). - --define(is_lowercase_char(X), (X > 96 andalso X < 123)). --define(is_underscore_char(X), (X == 95)). --define(is_digit_char(X), (X > 47 andalso X < 58)). --define(could_be_record(Tuple), - erlang:is_tuple(Tuple) andalso - erlang:is_atom(erlang:element(1, Tuple)) andalso - erlang:element(1, Tuple) =/= false andalso - erlang:element(1, Tuple) =/= true andalso - erlang:element(1, Tuple) =/= nil -). --define(is_atom_char(C), - (?is_lowercase_char(C) orelse - ?is_underscore_char(C) orelse - ?is_digit_char(C)) -). - --define(grey, "\e[90m"). --define(reset_color, "\e[39m"). - -echo(Value, File, Line) -> - StringLine = erlang:integer_to_list(Line), - StringValue = echo@inspect(Value), - io:put_chars( - standard_error, - [?grey, File, $:, StringLine, ?reset_color, $\n, StringValue, $\n] - ), - Value. - -echo@inspect(Value) -> - case Value of - nil -> "Nil"; - true -> "True"; - false -> "False"; - Int when erlang:is_integer(Int) -> erlang:integer_to_list(Int); - Float when erlang:is_float(Float) -> io_lib_format:fwrite_g(Float); - Binary when erlang:is_binary(Binary) -> inspect@binary(Binary); - Bits when erlang:is_bitstring(Bits) -> inspect@bit_array(Bits); - Atom when erlang:is_atom(Atom) -> inspect@atom(Atom); - List when erlang:is_list(List) -> inspect@list(List); - Map when erlang:is_map(Map) -> inspect@map(Map); - Record when ?could_be_record(Record) -> inspect@record(Record); - Tuple when erlang:is_tuple(Tuple) -> inspect@tuple(Tuple); - Function when erlang:is_function(Function) -> inspect@function(Function); - Any -> ["//erl(", io_lib:format("~p", [Any]), ")"] - end. - -inspect@bit_array(Bits) -> - Pieces = inspect@bit_array_pieces(Bits, []), - Inner = lists:join(", ", lists:reverse(Pieces)), - ["<<", Inner, ">>"]. - -inspect@bit_array_pieces(Bits, Acc) -> - case Bits of - <<>> -> - Acc; - <> -> - inspect@bit_array_pieces(Rest, [erlang:integer_to_binary(Byte) | Acc]); - _ -> - Size = erlang:bit_size(Bits), - <> = Bits, - SizeString = [":size(", erlang:integer_to_binary(Size), ")"], - Piece = [erlang:integer_to_binary(RemainingBits), SizeString], - [Piece | Acc] - end. - -inspect@binary(Binary) -> - case inspect@maybe_utf8_string(Binary, <<>>) of - {ok, InspectedUtf8String} -> - InspectedUtf8String; - {error, not_a_utf8_string} -> - Segments = [erlang:integer_to_list(X) || <> <= Binary], - ["<<", lists:join(", ", Segments), ">>"] - end. - -inspect@atom(Atom) -> - Binary = erlang:atom_to_binary(Atom), - case inspect@maybe_gleam_atom(Binary, none, <<>>) of - {ok, Inspected} -> Inspected; - {error, _} -> ["atom.create_from_string(\"", Binary, "\")"] - end. - -inspect@list(List) -> - case inspect@proper_or_improper_list(List) of - {proper, Elements} -> ["[", Elements, "]"]; - {improper, Elements} -> ["//erl([", Elements, "])"] - end. - -inspect@map(Map) -> - Fields = [ - [<<"#(">>, echo@inspect(Key), <<", ">>, echo@inspect(Value), <<")">>] - || {Key, Value} <- maps:to_list(Map) - ], - ["dict.from_list([", lists:join(", ", Fields), "])"]. - -inspect@record(Record) -> - [Atom | ArgsList] = erlang:tuple_to_list(Record), - Args = lists:join(", ", lists:map(fun echo@inspect/1, ArgsList)), - [echo@inspect(Atom), "(", Args, ")"]. - -inspect@tuple(Tuple) -> - Elements = lists:map(fun echo@inspect/1, erlang:tuple_to_list(Tuple)), - ["#(", lists:join(", ", Elements), ")"]. - -inspect@function(Function) -> - {arity, Arity} = erlang:fun_info(Function, arity), - ArgsAsciiCodes = lists:seq($a, $a + Arity - 1), - Args = lists:join(", ", lists:map(fun(Arg) -> <> end, ArgsAsciiCodes)), - ["//fn(", Args, ") { ... }"]. - -inspect@maybe_utf8_string(Binary, Acc) -> - case Binary of - <<>> -> - {ok, <<$", Acc/binary, $">>}; - <> -> - Escaped = inspect@escape_grapheme(First), - inspect@maybe_utf8_string(Rest, <>); - _ -> - {error, not_a_utf8_string} - end. - -inspect@escape_grapheme(Char) -> - case Char of - $" -> <<$\\, $">>; - $\\ -> <<$\\, $\\>>; - $\r -> <<$\\, $r>>; - $\n -> <<$\\, $n>>; - $\t -> <<$\\, $t>>; - $\f -> <<$\\, $f>>; - X when X > 126, X < 160 -> inspect@convert_to_u(X); - X when X < 32 -> inspect@convert_to_u(X); - Other -> <> - end. - -inspect@convert_to_u(Code) -> - erlang:list_to_binary(io_lib:format("\\u{~4.16.0B}", [Code])). - -inspect@proper_or_improper_list(List) -> - case List of - [] -> - {proper, []}; - [First] -> - {proper, [echo@inspect(First)]}; - [First | Rest] when erlang:is_list(Rest) -> - {Kind, Inspected} = inspect@proper_or_improper_list(Rest), - {Kind, [echo@inspect(First), ", " | Inspected]}; - [First | ImproperRest] -> - {improper, [echo@inspect(First), " | ", echo@inspect(ImproperRest)]} - end. - -inspect@maybe_gleam_atom(Atom, PrevChar, Acc) -> - case {Atom, PrevChar} of - {<<>>, none} -> - {error, nil}; - {<>, none} when ?is_digit_char(First) -> - {error, nil}; - {<<"_", _/binary>>, none} -> - {error, nil}; - {<<"_">>, _} -> - {error, nil}; - {<<"_", _/binary>>, $_} -> - {error, nil}; - {<>, _} when not ?is_atom_char(First) -> - {error, nil}; - {<>, none} -> - inspect@maybe_gleam_atom(Rest, First, <>); - {<<"_", Rest/binary>>, _} -> - inspect@maybe_gleam_atom(Rest, $_, Acc); - {<>, $_} -> - inspect@maybe_gleam_atom(Rest, First, <>); - {<>, _} -> - inspect@maybe_gleam_atom(Rest, First, <>); - {<<>>, _} -> - {ok, Acc}; - _ -> - erlang:throw({gleam_error, echo, Atom, PrevChar, Acc}) - end. - -inspect@uppercase(X) -> X - 32. - diff --git a/test-output/cases/echo_float/build/dev/erlang/echo_float/ebin/echo_float.app b/test-output/cases/echo_float/build/dev/erlang/echo_float/ebin/echo_float.app deleted file mode 100644 index 10364b00b78..00000000000 --- a/test-output/cases/echo_float/build/dev/erlang/echo_float/ebin/echo_float.app +++ /dev/null @@ -1,7 +0,0 @@ -{application, echo_float, [ - {vsn, "1.0.0"}, - {applications, []}, - {description, ""}, - {modules, [main]}, - {registered, []} -]}. diff --git a/test-output/cases/echo_float/build/dev/erlang/gleam_version b/test-output/cases/echo_float/build/dev/erlang/gleam_version deleted file mode 100644 index 3e1ad720b13..00000000000 --- a/test-output/cases/echo_float/build/dev/erlang/gleam_version +++ /dev/null @@ -1 +0,0 @@ -1.5.0 \ No newline at end of file diff --git a/test-output/cases/echo_float/build/dev/javascript/echo_float/_gleam_artefacts/main.cache b/test-output/cases/echo_float/build/dev/javascript/echo_float/_gleam_artefacts/main.cache deleted file mode 100644 index 0312ec93c05..00000000000 Binary files a/test-output/cases/echo_float/build/dev/javascript/echo_float/_gleam_artefacts/main.cache and /dev/null differ diff --git a/test-output/cases/echo_float/build/dev/javascript/echo_float/_gleam_artefacts/main.cache_meta b/test-output/cases/echo_float/build/dev/javascript/echo_float/_gleam_artefacts/main.cache_meta deleted file mode 100644 index 60b0815764f..00000000000 Binary files a/test-output/cases/echo_float/build/dev/javascript/echo_float/_gleam_artefacts/main.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_float/build/dev/javascript/echo_float/_gleam_artefacts/main.cache_warnings b/test-output/cases/echo_float/build/dev/javascript/echo_float/_gleam_artefacts/main.cache_warnings deleted file mode 100644 index 1b1cb4d44c5..00000000000 Binary files a/test-output/cases/echo_float/build/dev/javascript/echo_float/_gleam_artefacts/main.cache_warnings and /dev/null differ diff --git a/test-output/cases/echo_float/build/dev/javascript/echo_float/gleam.main.mjs b/test-output/cases/echo_float/build/dev/javascript/echo_float/gleam.main.mjs deleted file mode 100644 index e230911e646..00000000000 --- a/test-output/cases/echo_float/build/dev/javascript/echo_float/gleam.main.mjs +++ /dev/null @@ -1,2 +0,0 @@ -import { main } from "./main.mjs"; -main(); diff --git a/test-output/cases/echo_float/build/dev/javascript/echo_float/gleam.mjs b/test-output/cases/echo_float/build/dev/javascript/echo_float/gleam.mjs deleted file mode 100644 index 197cbbc35d4..00000000000 --- a/test-output/cases/echo_float/build/dev/javascript/echo_float/gleam.mjs +++ /dev/null @@ -1 +0,0 @@ -export * from "../prelude.mjs"; diff --git a/test-output/cases/echo_float/build/dev/javascript/echo_float/main.mjs b/test-output/cases/echo_float/build/dev/javascript/echo_float/main.mjs deleted file mode 100644 index 4719c06941a..00000000000 --- a/test-output/cases/echo_float/build/dev/javascript/echo_float/main.mjs +++ /dev/null @@ -1,129 +0,0 @@ -import { - BitArray as $BitArray, - List as $List, - UtfCodepoint as $UtfCodepoint, - CustomType as $CustomType, -} from "./gleam.mjs"; - -export function main() { - echo(1.0, "src/main.gleam", 2); - echo(2.1, "src/main.gleam", 3); - return echo(11.11, "src/main.gleam", 4); -} - -function echo(value, file, line) { - const grey = "\u001b[90m"; - const reset_color = "\u001b[39m"; - const file_line = `${file}:${line}`; - const string_value = echo$inspect(value); - - if (typeof process === "object" && process.stderr?.write) { - // If we're in Node.js, use `stderr` - const string = `${grey}${file_line}${reset_color}\n${string_value}\n`; - process.stderr.write(string); - } else if (typeof Deno === "object") { - // If we're in Deno, use `stderr` - const string = `${grey}${file_line}${reset_color}\n${string_value}\n`; - Deno.stderr.writeSync(new TextEncoder().encode(string)); - } else { - // Otherwise, use `console.log` - // The browser's console.log doesn't support ansi escape codes - const string = `${file_line}\n${string_value}`; - console.log(string); - } - - return value; -} - -function echo$inspectString(str) { - let new_str = '"'; - for (let i = 0; i < str.length; i++) { - let char = str[i]; - if (char == "\n") new_str += "\\n"; - else if (char == "\r") new_str += "\\r"; - else if (char == "\t") new_str += "\\t"; - else if (char == "\f") new_str += "\\f"; - else if (char == "\\") new_str += "\\\\"; - else if (char == '"') new_str += '\\"'; - else if (char < " " || (char > "~" && char < "\u{00A0}")) { - new_str += "\\u{" + char.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0") + "}"; - } else { - new_str += char; - } - } - new_str += '"'; - return new_str; -} - -function echo$inspectDict(map) { - let body = "dict.from_list(["; - let first = true; - map.forEach((value, key) => { - if (!first) body = body + ", "; - body = body + "#(" + echo$inspect(key) + ", " + echo$inspect(value) + ")"; - first = false; - }); - return body + "])"; -} - -function echo$inspectCustomType(record) { - const props = Object.keys(record) - .map((label) => { - const value = echo$inspect(record[label]); - return isNaN(parseInt(label)) ? `${label}: ${value}` : value; - }) - .join(", "); - return props ? `${record.constructor.name}(${props})` : record.constructor.name; -} - -function echo$inspectObject(v) { - const name = Object.getPrototypeOf(v)?.constructor?.name || "Object"; - const props = []; - for (const k of Object.keys(v)) { - props.push(`${echo$inspect(k)}: ${echo$inspect(v[k])}`); - } - const body = props.length ? " " + props.join(", ") + " " : ""; - const head = name === "Object" ? "" : name + " "; - return `//js(${head}{${body}})`; -} - -function echo$inspect(v) { - const t = typeof v; - if (v === true) return "True"; - if (v === false) return "False"; - if (v === null) return "//js(null)"; - if (v === undefined) return "Nil"; - if (t === "string") return echo$inspectString(v); - if (t === "bigint" || t === "number") return v.toString(); - if (Array.isArray(v)) return `#(${v.map(echo$inspect).join(", ")})`; - if (v instanceof $List) return `[${v.toArray().map(echo$inspect).join(", ")}]`; - if (v instanceof $UtfCodepoint) return `//utfcodepoint(${String.fromCodePoint(v.value)})`; - if (v instanceof $BitArray) return `<<${Array.from(v.buffer).join(", ")}>>`; - if (v instanceof $CustomType) return echo$inspectCustomType(v); - if (echo$isDict(v)) return echo$inspectDict(v); - if (v instanceof Set) return `//js(Set(${[...v].map(echo$inspect).join(", ")}))`; - if (v instanceof RegExp) return `//js(${v})`; - if (v instanceof Date) return `//js(Date("${v.toISOString()}"))`; - if (v instanceof Function) { - const args = []; - for (const i of Array(v.length).keys()) args.push(String.fromCharCode(i + 97)); - return `//fn(${args.join(", ")}) { ... }`; - } - return echo$inspectObject(v); -} - -function echo$isDict(value) { - try { - // We can only check if an object is a stdlib Dict if it is one of the - // project's dependencies. - // The `Dict` class is the default export of `stdlib/dict.mjs` - // that we import as `$stdlib$dict`. - return value instanceof $stdlib$dict.default; - } catch { - // If stdlib is not one of the project's dependencies then `$stdlib$dict` - // will not have been imported and the check will throw an exception meaning - // we can't check if something is actually a `Dict`. - return false; - } -} - diff --git a/test-output/cases/echo_float/build/dev/javascript/gleam_version b/test-output/cases/echo_float/build/dev/javascript/gleam_version deleted file mode 100644 index 3e1ad720b13..00000000000 --- a/test-output/cases/echo_float/build/dev/javascript/gleam_version +++ /dev/null @@ -1 +0,0 @@ -1.5.0 \ No newline at end of file diff --git a/test-output/cases/echo_float/build/dev/javascript/prelude.mjs b/test-output/cases/echo_float/build/dev/javascript/prelude.mjs deleted file mode 100644 index d2adeef273f..00000000000 --- a/test-output/cases/echo_float/build/dev/javascript/prelude.mjs +++ /dev/null @@ -1,455 +0,0 @@ -// Values marked with @internal are not part of the public API and may change -// without notice. - -export class CustomType { - withFields(fields) { - let properties = Object.keys(this).map((label) => - label in fields ? fields[label] : this[label], - ); - return new this.constructor(...properties); - } -} - -export class List { - static fromArray(array, tail) { - let t = tail || new Empty(); - for (let i = array.length - 1; i >= 0; --i) { - t = new NonEmpty(array[i], t); - } - return t; - } - - [Symbol.iterator]() { - return new ListIterator(this); - } - - toArray() { - return [...this]; - } - - // @internal - atLeastLength(desired) { - for (let _ of this) { - if (desired <= 0) return true; - desired--; - } - return desired <= 0; - } - - // @internal - hasLength(desired) { - for (let _ of this) { - if (desired <= 0) return false; - desired--; - } - return desired === 0; - } - - // @internal - countLength() { - let length = 0; - for (let _ of this) length++; - return length; - } -} - -// @internal -export function prepend(element, tail) { - return new NonEmpty(element, tail); -} - -export function toList(elements, tail) { - return List.fromArray(elements, tail); -} - -// @internal -class ListIterator { - #current; - - constructor(current) { - this.#current = current; - } - - next() { - if (this.#current instanceof Empty) { - return { done: true }; - } else { - let { head, tail } = this.#current; - this.#current = tail; - return { value: head, done: false }; - } - } -} - -export class Empty extends List {} - -export class NonEmpty extends List { - constructor(head, tail) { - super(); - this.head = head; - this.tail = tail; - } -} - -export class BitArray { - constructor(buffer) { - if (!(buffer instanceof Uint8Array)) { - throw "BitArray can only be constructed from a Uint8Array"; - } - this.buffer = buffer; - } - - // @internal - get length() { - return this.buffer.length; - } - - // @internal - byteAt(index) { - return this.buffer[index]; - } - - // @internal - floatFromSlice(start, end, isBigEndian) { - return byteArrayToFloat(this.buffer, start, end, isBigEndian); - } - - // @internal - intFromSlice(start, end, isBigEndian, isSigned) { - return byteArrayToInt(this.buffer, start, end, isBigEndian, isSigned); - } - - // @internal - binaryFromSlice(start, end) { - return new BitArray(this.buffer.slice(start, end)); - } - - // @internal - sliceAfter(index) { - return new BitArray(this.buffer.slice(index)); - } -} - -export class UtfCodepoint { - constructor(value) { - this.value = value; - } -} - -// @internal -export function toBitArray(segments) { - if (segments.length === 0) { - return new BitArray(new Uint8Array()); - } - - if (segments.length === 1) { - // When there is a single Uint8Array segment, pass it directly to the bit - // array constructor to avoid a copy - if (segments[0] instanceof Uint8Array) { - return new BitArray(segments[0]); - } - - return new BitArray(new Uint8Array(segments)); - } - - // Count the total number of bytes, and check if there are any Uint8Array - // segments - let bytes = 0; - let hasUint8ArraySegment = false; - for (const segment of segments) { - if (segment instanceof Uint8Array) { - bytes += segment.byteLength; - hasUint8ArraySegment = true; - } else { - bytes++; - } - } - - // If there aren't any Uint8Array segments then pass the segments array - // directly to the Uint8Array constructor - if (!hasUint8ArraySegment) { - return new BitArray(new Uint8Array(segments)); - } - - // Copy the segments into a Uint8Array - let u8Array = new Uint8Array(bytes); - let cursor = 0; - for (let segment of segments) { - if (segment instanceof Uint8Array) { - u8Array.set(segment, cursor); - cursor += segment.byteLength; - } else { - u8Array[cursor] = segment; - cursor++; - } - } - - return new BitArray(u8Array); -} - -// @internal -// Derived from this answer https://stackoverflow.com/questions/8482309/converting-javascript-integer-to-byte-array-and-back -export function sizedInt(value, size, isBigEndian) { - if (size < 0) { - return new Uint8Array(); - } - if (size % 8 != 0) { - const msg = `Bit arrays must be byte aligned on JavaScript, got size of ${size} bits`; - throw new globalThis.Error(msg); - } - - const byteArray = new Uint8Array(size / 8); - - // Convert negative number to two's complement representation - if (value < 0) { - value = 2 ** size + value; - } - - if (isBigEndian) { - for (let i = byteArray.length - 1; i >= 0; i--) { - const byte = value % 256; - byteArray[i] = byte; - value = (value - byte) / 256; - } - } else { - for (let i = 0; i < byteArray.length; i++) { - const byte = value % 256; - byteArray[i] = byte; - value = (value - byte) / 256; - } - } - - return byteArray; -} - -// @internal -export function byteArrayToInt(byteArray, start, end, isBigEndian, isSigned) { - let value = 0; - - // Read bytes as an unsigned integer value - if (isBigEndian) { - for (let i = start; i < end; i++) { - value = value * 256 + byteArray[i]; - } - } else { - for (let i = end - 1; i >= start; i--) { - value = value * 256 + byteArray[i]; - } - } - - if (isSigned) { - const byteSize = end - start; - - const highBit = 2 ** (byteSize * 8 - 1); - - // If the high bit is set and this is a signed integer, reinterpret as - // two's complement - if (value >= highBit) { - value -= highBit * 2; - } - } - - return value; -} - -// @internal -export function byteArrayToFloat(byteArray, start, end, isBigEndian) { - const view = new DataView(byteArray.buffer); - - const byteSize = end - start; - - if (byteSize === 8) { - return view.getFloat64(start, !isBigEndian); - } else if (byteSize === 4) { - return view.getFloat32(start, !isBigEndian); - } else { - const msg = `Sized floats must be 32-bit or 64-bit on JavaScript, got size of ${byteSize * 8} bits`; - throw new globalThis.Error(msg); - } -} - -// @internal -export function stringBits(string) { - return new TextEncoder().encode(string); -} - -// @internal -export function codepointBits(codepoint) { - return stringBits(String.fromCodePoint(codepoint.value)); -} - -// @internal -export function sizedFloat(float, size, isBigEndian) { - if (size !== 32 && size !== 64) { - const msg = `Sized floats must be 32-bit or 64-bit on JavaScript, got size of ${size} bits`; - throw new globalThis.Error(msg); - } - - const byteArray = new Uint8Array(size / 8); - - const view = new DataView(byteArray.buffer); - - if (size == 64) { - view.setFloat64(0, float, !isBigEndian); - } else if (size === 32) { - view.setFloat32(0, float, !isBigEndian); - } - - return byteArray; -} - -export class Result extends CustomType { - // @internal - static isResult(data) { - return data instanceof Result; - } -} - -export class Ok extends Result { - constructor(value) { - super(); - this[0] = value; - } - - // @internal - isOk() { - return true; - } -} - -export class Error extends Result { - constructor(detail) { - super(); - this[0] = detail; - } - - // @internal - isOk() { - return false; - } -} - -export function isEqual(x, y) { - let values = [x, y]; - - while (values.length) { - let a = values.pop(); - let b = values.pop(); - if (a === b) continue; - - if (!isObject(a) || !isObject(b)) return false; - let unequal = - !structurallyCompatibleObjects(a, b) || - unequalDates(a, b) || - unequalBuffers(a, b) || - unequalArrays(a, b) || - unequalMaps(a, b) || - unequalSets(a, b) || - unequalRegExps(a, b); - if (unequal) return false; - - const proto = Object.getPrototypeOf(a); - if (proto !== null && typeof proto.equals === "function") { - try { - if (a.equals(b)) continue; - else return false; - } catch {} - } - - let [keys, get] = getters(a); - for (let k of keys(a)) { - values.push(get(a, k), get(b, k)); - } - } - - return true; -} - -function getters(object) { - if (object instanceof Map) { - return [(x) => x.keys(), (x, y) => x.get(y)]; - } else { - let extra = object instanceof globalThis.Error ? ["message"] : []; - return [(x) => [...extra, ...Object.keys(x)], (x, y) => x[y]]; - } -} - -function unequalDates(a, b) { - return a instanceof Date && (a > b || a < b); -} - -function unequalBuffers(a, b) { - return ( - a.buffer instanceof ArrayBuffer && - a.BYTES_PER_ELEMENT && - !(a.byteLength === b.byteLength && a.every((n, i) => n === b[i])) - ); -} - -function unequalArrays(a, b) { - return Array.isArray(a) && a.length !== b.length; -} - -function unequalMaps(a, b) { - return a instanceof Map && a.size !== b.size; -} - -function unequalSets(a, b) { - return ( - a instanceof Set && (a.size != b.size || [...a].some((e) => !b.has(e))) - ); -} - -function unequalRegExps(a, b) { - return a instanceof RegExp && (a.source !== b.source || a.flags !== b.flags); -} - -function isObject(a) { - return typeof a === "object" && a !== null; -} - -function structurallyCompatibleObjects(a, b) { - if (typeof a !== "object" && typeof b !== "object" && (!a || !b)) - return false; - - let nonstructural = [Promise, WeakSet, WeakMap, Function]; - if (nonstructural.some((c) => a instanceof c)) return false; - - return a.constructor === b.constructor; -} - -// @internal -export function remainderInt(a, b) { - if (b === 0) { - return 0; - } else { - return a % b; - } -} - -// @internal -export function divideInt(a, b) { - return Math.trunc(divideFloat(a, b)); -} - -// @internal -export function divideFloat(a, b) { - if (b === 0) { - return 0; - } else { - return a / b; - } -} - -// @internal -export function makeError(variant, module, line, fn, message, extra) { - let error = new globalThis.Error(message); - error.gleam_error = variant; - error.module = module; - error.line = line; - error.function = fn; - // TODO: Remove this with Gleam v2.0.0 - error.fn = fn; - for (let k in extra) error[k] = extra[k]; - return error; -} diff --git a/test-output/cases/echo_float/build/packages/packages.toml b/test-output/cases/echo_float/build/packages/packages.toml deleted file mode 100644 index e74c18552bb..00000000000 --- a/test-output/cases/echo_float/build/packages/packages.toml +++ /dev/null @@ -1 +0,0 @@ -[packages] diff --git a/test-output/cases/echo_float/manifest.toml b/test-output/cases/echo_float/manifest.toml deleted file mode 100644 index c5d779a3f81..00000000000 --- a/test-output/cases/echo_float/manifest.toml +++ /dev/null @@ -1,7 +0,0 @@ -# This file was generated by Gleam -# You typically do not need to edit this file - -packages = [ -] - -[requirements] diff --git a/test-output/cases/echo_function/build/dev/erlang/echo_custom_type/_gleam_artefacts/echo_custom_type@@main.erl b/test-output/cases/echo_function/build/dev/erlang/echo_custom_type/_gleam_artefacts/echo_custom_type@@main.erl deleted file mode 100644 index 62cb39e944a..00000000000 --- a/test-output/cases/echo_function/build/dev/erlang/echo_custom_type/_gleam_artefacts/echo_custom_type@@main.erl +++ /dev/null @@ -1,99 +0,0 @@ --module('echo_custom_type@@main'). --export([run/1]). - --define(red, "\e[31;1m"). --define(grey, "\e[90m"). --define(reset_color, "\e[39m"). --define(reset_all, "\e[0m"). - -run(Module) -> - io:setopts(standard_io, [binary, {encoding, utf8}]), - io:setopts(standard_error, [{encoding, utf8}]), - process_flag(trap_exit, true), - Pid = spawn_link(fun() -> run_module(Module) end), - receive - {'EXIT', Pid, {Reason, StackTrace}} -> - print_error(exit, Reason, StackTrace), - init:stop(1) - end. - -run_module(Module) -> - try - {ok, _} = application:ensure_all_started('echo_custom_type'), - erlang:process_flag(trap_exit, false), - Module:main(), - erlang:halt(0) - catch - Class:Reason:StackTrace -> - print_error(Class, Reason, StackTrace), - init:stop(1) - end. - -print_error(Class, Error, Stacktrace) -> - Printed = [ - ?red, "runtime error", ?reset_color, ": ", error_class(Class, Error), ?reset_all, - "\n\n", - error_message(Error), - "\n\n", - error_details(Class, Error), - "stacktrace:\n", - [error_frame(Line) || Line <- refine_first(Error, Stacktrace)] - ], - io:format(standard_error, "~ts~n", [Printed]). - -refine_first(#{gleam_error := _, line := L}, [{M, F, A, [{file, Fi} | _]} | S]) -> - [{M, F, A, [{file, Fi}, {line, L}]} | S]; -refine_first(_, S) -> - S. - -error_class(_, #{gleam_error := panic}) -> "panic"; -error_class(_, #{gleam_error := todo}) -> "todo"; -error_class(_, #{gleam_error := let_assert}) -> "let assert"; -error_class(Class, _) -> ["Erlang ", atom_to_binary(Class)]. - -error_message(#{gleam_error := _, message := M}) -> - M; -error_message(undef) -> - <<"A function was called but it did not exist."/utf8 >>; -error_message({case_clause, _}) -> - <<"No pattern matched in an Erlang case expression."/utf8>>; -error_message({badmatch, _}) -> - <<"An Erlang assignment pattern did not match."/utf8>>; -error_message(function_clause) -> - <<"No Erlang function clause matched the arguments it was called with."/utf8>>; -error_message(_) -> - <<"An error occurred outside of Gleam."/utf8>>. - -error_details(_, #{gleam_error := let_assert, value := V}) -> - ["unmatched value:\n ", print_term(V), $\n, $\n]; -error_details(_, {case_clause, V}) -> - ["unmatched value:\n ", print_term(V), $\n, $\n]; -error_details(_, {badmatch, V}) -> - ["unmatched value:\n ", print_term(V), $\n, $\n]; -error_details(_, #{gleam_error := _}) -> - []; -error_details(error, function_clause) -> - []; -error_details(error, undef) -> - []; -error_details(C, E) -> - ["erlang:", atom_to_binary(C), $(, print_term(E), $), $\n, $\n]. - -print_term(T) -> - try - gleam@string:inspect(T) - catch - _:_ -> io_lib:format("~p", [T]) - end. - -error_frame({?MODULE, _, _, _}) -> []; -error_frame({erl_eval, _, _, _}) -> []; -error_frame({init, _, _, _}) -> []; -error_frame({M, F, _, O}) -> - M1 = string:replace(atom_to_binary(M), "@", "/", all), - [" ", M1, $., atom_to_binary(F), error_frame_end(O), $\n]. - -error_frame_end([{file, Fi}, {line, L} | _]) -> - [?grey, $\s, Fi, $:, integer_to_binary(L), ?reset_all]; -error_frame_end(_) -> - [?grey, " unknown source", ?reset_all]. \ No newline at end of file diff --git a/test-output/cases/echo_function/build/dev/erlang/echo_custom_type/_gleam_artefacts/gleam@@compile.erl b/test-output/cases/echo_function/build/dev/erlang/echo_custom_type/_gleam_artefacts/gleam@@compile.erl deleted file mode 100644 index 3e0a645b737..00000000000 --- a/test-output/cases/echo_function/build/dev/erlang/echo_custom_type/_gleam_artefacts/gleam@@compile.erl +++ /dev/null @@ -1,163 +0,0 @@ -#!/usr/bin/env escript --mode(compile). - -% TODO: Don't concurrently print warnings and errors -% TODO: Some tests - -main(_) -> compile_package_loop(). - -compile_package_loop() -> - case file:read_line(standard_io) of - eof -> ok; - {ok, Line} -> - Chars = unicode:characters_to_list(Line), - {ok, Tokens, _} = erl_scan:string(Chars), - {ok, {Lib, Out, Modules}} = erl_parse:parse_term(Tokens), - case compile_package(Lib, Out, Modules) of - ok -> io:put_chars("gleam-compile-result-ok\n"); - err -> io:put_chars("gleam-compile-result-error\n") - end, - compile_package_loop() - end. - -compile_package(Lib, Out, Modules) -> - IsElixirModule = fun(Module) -> - filename:extension(Module) =:= ".ex" - end, - {ElixirModules, ErlangModules} = lists:partition(IsElixirModule, Modules), - ok = configure_logging(), - ok = add_lib_to_erlang_path(Lib), - ok = filelib:ensure_dir([Out, $/]), - {ErlangOk, _ErlangBeams} = compile_erlang(ErlangModules, Out), - {ElixirOk, _ElixirBeams} = case ErlangOk of - true -> compile_elixir(ElixirModules, Out); - false -> {false, []} - end, - ok = del_lib_from_erlang_path(Lib), - case ErlangOk and ElixirOk of - true -> ok; - false -> err - end. - -compile_erlang(Modules, Out) -> - Workers = start_compiler_workers(Out), - ok = producer_loop(Modules, Workers), - collect_results({true, []}). - -collect_results(Acc = {Result, Beams}) -> - receive - {compiled, Beam} -> collect_results({Result, [Beam | Beams]}); - failed -> collect_results({false, Beams}) - after 0 -> Acc - end. - -producer_loop([], 0) -> - ok; -producer_loop([], Workers) -> - receive - {work_please, _} -> producer_loop([], Workers - 1) - end; -producer_loop([Module | Modules], Workers) -> - receive - {work_please, Worker} -> - erlang:send(Worker, {module, Module}), - producer_loop(Modules, Workers) - end. - -start_compiler_workers(Out) -> - Parent = self(), - NumSchedulers = erlang:system_info(schedulers), - SpawnWorker = fun(_) -> - erlang:spawn_link(fun() -> worker_loop(Parent, Out) end) - end, - lists:foreach(SpawnWorker, lists:seq(1, NumSchedulers)), - NumSchedulers. - -worker_loop(Parent, Out) -> - Options = [report_errors, report_warnings, debug_info, {outdir, Out}], - erlang:send(Parent, {work_please, self()}), - receive - {module, Module} -> - log({compiling, Module}), - case compile:file(Module, Options) of - {ok, ModuleName} -> - Beam = filename:join(Out, ModuleName) ++ ".beam", - Message = {compiled, Beam}, - log(Message), - erlang:send(Parent, Message); - error -> - log({failed, Module}), - erlang:send(Parent, failed) - end, - worker_loop(Parent, Out) - end. - -compile_elixir(Modules, Out) -> - Error = [ - "The program elixir was not found. Is it installed?", - $\n, - "Documentation for installing Elixir can be viewed here:", - $\n, - "https://elixir-lang.org/install.html" - ], - case Modules of - [] -> {true, []}; - _ -> - log({starting, "compiler.app"}), - ok = application:start(compiler), - log({starting, "elixir.app"}), - case application:start(elixir) of - ok -> do_compile_elixir(Modules, Out); - _ -> - io:put_chars(standard_error, [Error, $\n]), - {false, []} - end - end. - -do_compile_elixir(Modules, Out) -> - ModuleBins = lists:map(fun(Module) -> - log({compiling, Module}), - list_to_binary(Module) - end, Modules), - OutBin = list_to_binary(Out), - Options = [{dest, OutBin}], - % Silence "redefining module" warnings. - % Compiled modules in the build directory are added to the code path. - % These warnings result from recompiling loaded modules. - % TODO: This line can likely be removed if/when the build directory is cleaned before every compilation. - 'Elixir.Code':compiler_options([{ignore_module_conflict, true}]), - case 'Elixir.Kernel.ParallelCompiler':compile_to_path(ModuleBins, OutBin, Options) of - {ok, ModuleAtoms, _} -> - ToBeam = fun(ModuleAtom) -> - Beam = filename:join(Out, atom_to_list(ModuleAtom)) ++ ".beam", - log({compiled, Beam}), - Beam - end, - {true, lists:map(ToBeam, ModuleAtoms)}; - {error, Errors, _} -> - % Log all filenames associated with modules that failed to compile. - % Note: The compiler prints compilation errors upon encountering them. - ErrorFiles = lists:usort([File || {File, _, _} <- Errors]), - Log = fun(File) -> - log({failed, binary_to_list(File)}) - end, - lists:foreach(Log, ErrorFiles), - {false, []}; - _ -> {false, []} - end. - -add_lib_to_erlang_path(Lib) -> - code:add_paths(filelib:wildcard([Lib, "/*/ebin"])). - -del_lib_from_erlang_path(Lib) -> - code:del_paths(filelib:wildcard([Lib, "/*/ebin"])). - -configure_logging() -> - Enabled = os:getenv("GLEAM_LOG") /= false, - persistent_term:put(gleam_logging_enabled, Enabled). - -log(Term) -> - case persistent_term:get(gleam_logging_enabled) of - true -> erlang:display(Term), ok; - false -> ok - end. diff --git a/test-output/cases/echo_function/build/dev/erlang/echo_custom_type/_gleam_artefacts/main.cache b/test-output/cases/echo_function/build/dev/erlang/echo_custom_type/_gleam_artefacts/main.cache deleted file mode 100644 index 8b13f95bf1c..00000000000 Binary files a/test-output/cases/echo_function/build/dev/erlang/echo_custom_type/_gleam_artefacts/main.cache and /dev/null differ diff --git a/test-output/cases/echo_function/build/dev/erlang/echo_custom_type/_gleam_artefacts/main.cache_meta b/test-output/cases/echo_function/build/dev/erlang/echo_custom_type/_gleam_artefacts/main.cache_meta deleted file mode 100644 index f2b9f5e0ed4..00000000000 Binary files a/test-output/cases/echo_function/build/dev/erlang/echo_custom_type/_gleam_artefacts/main.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_function/build/dev/erlang/echo_custom_type/_gleam_artefacts/main.cache_warnings b/test-output/cases/echo_function/build/dev/erlang/echo_custom_type/_gleam_artefacts/main.cache_warnings deleted file mode 100644 index 1b1cb4d44c5..00000000000 Binary files a/test-output/cases/echo_function/build/dev/erlang/echo_custom_type/_gleam_artefacts/main.cache_warnings and /dev/null differ diff --git a/test-output/cases/echo_function/build/dev/erlang/echo_custom_type/_gleam_artefacts/main.erl b/test-output/cases/echo_function/build/dev/erlang/echo_custom_type/_gleam_artefacts/main.erl deleted file mode 100644 index e70ccaac8d1..00000000000 --- a/test-output/cases/echo_function/build/dev/erlang/echo_custom_type/_gleam_artefacts/main.erl +++ /dev/null @@ -1,195 +0,0 @@ --module(main). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([main/0]). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_function/src/main.gleam", 6). --spec private() -> integer(). -private() -> - 1. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_function/src/main.gleam", 1). --spec main() -> fun(() -> integer()). -main() -> - echo(fun(N) -> N + 1 end, "src/main.gleam", 2), - echo(fun private/0, "src/main.gleam", 3). - --define(is_lowercase_char(X), (X > 96 andalso X < 123)). --define(is_underscore_char(X), (X == 95)). --define(is_digit_char(X), (X > 47 andalso X < 58)). --define(could_be_record(Tuple), - erlang:is_tuple(Tuple) andalso - erlang:is_atom(erlang:element(1, Tuple)) andalso - erlang:element(1, Tuple) =/= false andalso - erlang:element(1, Tuple) =/= true andalso - erlang:element(1, Tuple) =/= nil -). --define(is_atom_char(C), - (?is_lowercase_char(C) orelse - ?is_underscore_char(C) orelse - ?is_digit_char(C)) -). - --define(grey, "\e[90m"). --define(reset_color, "\e[39m"). - -echo(Value, File, Line) -> - StringLine = erlang:integer_to_list(Line), - StringValue = echo@inspect(Value), - io:put_chars( - standard_error, - [?grey, File, $:, StringLine, ?reset_color, $\n, StringValue, $\n] - ), - Value. - -echo@inspect(Value) -> - case Value of - nil -> "Nil"; - true -> "True"; - false -> "False"; - Int when erlang:is_integer(Int) -> erlang:integer_to_list(Int); - Float when erlang:is_float(Float) -> io_lib_format:fwrite_g(Float); - Binary when erlang:is_binary(Binary) -> inspect@binary(Binary); - Bits when erlang:is_bitstring(Bits) -> inspect@bit_array(Bits); - Atom when erlang:is_atom(Atom) -> inspect@atom(Atom); - List when erlang:is_list(List) -> inspect@list(List); - Map when erlang:is_map(Map) -> inspect@map(Map); - Record when ?could_be_record(Record) -> inspect@record(Record); - Tuple when erlang:is_tuple(Tuple) -> inspect@tuple(Tuple); - Function when erlang:is_function(Function) -> inspect@function(Function); - Any -> ["//erl(", io_lib:format("~p", [Any]), ")"] - end. - -inspect@bit_array(Bits) -> - Pieces = inspect@bit_array_pieces(Bits, []), - Inner = lists:join(", ", lists:reverse(Pieces)), - ["<<", Inner, ">>"]. - -inspect@bit_array_pieces(Bits, Acc) -> - case Bits of - <<>> -> - Acc; - <> -> - inspect@bit_array_pieces(Rest, [erlang:integer_to_binary(Byte) | Acc]); - _ -> - Size = erlang:bit_size(Bits), - <> = Bits, - SizeString = [":size(", erlang:integer_to_binary(Size), ")"], - Piece = [erlang:integer_to_binary(RemainingBits), SizeString], - [Piece | Acc] - end. - -inspect@binary(Binary) -> - case inspect@maybe_utf8_string(Binary, <<>>) of - {ok, InspectedUtf8String} -> - InspectedUtf8String; - {error, not_a_utf8_string} -> - Segments = [erlang:integer_to_list(X) || <> <= Binary], - ["<<", lists:join(", ", Segments), ">>"] - end. - -inspect@atom(Atom) -> - Binary = erlang:atom_to_binary(Atom), - case inspect@maybe_gleam_atom(Binary, none, <<>>) of - {ok, Inspected} -> Inspected; - {error, _} -> ["atom.create_from_string(\"", Binary, "\")"] - end. - -inspect@list(List) -> - case inspect@proper_or_improper_list(List) of - {proper, Elements} -> ["[", Elements, "]"]; - {improper, Elements} -> ["//erl([", Elements, "])"] - end. - -inspect@map(Map) -> - Fields = [ - [<<"#(">>, echo@inspect(Key), <<", ">>, echo@inspect(Value), <<")">>] - || {Key, Value} <- maps:to_list(Map) - ], - ["dict.from_list([", lists:join(", ", Fields), "])"]. - -inspect@record(Record) -> - [Atom | ArgsList] = erlang:tuple_to_list(Record), - Args = lists:join(", ", lists:map(fun echo@inspect/1, ArgsList)), - [echo@inspect(Atom), "(", Args, ")"]. - -inspect@tuple(Tuple) -> - Elements = lists:map(fun echo@inspect/1, erlang:tuple_to_list(Tuple)), - ["#(", lists:join(", ", Elements), ")"]. - -inspect@function(Function) -> - {arity, Arity} = erlang:fun_info(Function, arity), - ArgsAsciiCodes = lists:seq($a, $a + Arity - 1), - Args = lists:join(", ", lists:map(fun(Arg) -> <> end, ArgsAsciiCodes)), - ["//fn(", Args, ") { ... }"]. - -inspect@maybe_utf8_string(Binary, Acc) -> - case Binary of - <<>> -> - {ok, <<$", Acc/binary, $">>}; - <> -> - Escaped = inspect@escape_grapheme(First), - inspect@maybe_utf8_string(Rest, <>); - _ -> - {error, not_a_utf8_string} - end. - -inspect@escape_grapheme(Char) -> - case Char of - $" -> <<$\\, $">>; - $\\ -> <<$\\, $\\>>; - $\r -> <<$\\, $r>>; - $\n -> <<$\\, $n>>; - $\t -> <<$\\, $t>>; - $\f -> <<$\\, $f>>; - X when X > 126, X < 160 -> inspect@convert_to_u(X); - X when X < 32 -> inspect@convert_to_u(X); - Other -> <> - end. - -inspect@convert_to_u(Code) -> - erlang:list_to_binary(io_lib:format("\\u{~4.16.0B}", [Code])). - -inspect@proper_or_improper_list(List) -> - case List of - [] -> - {proper, []}; - [First] -> - {proper, [echo@inspect(First)]}; - [First | Rest] when erlang:is_list(Rest) -> - {Kind, Inspected} = inspect@proper_or_improper_list(Rest), - {Kind, [echo@inspect(First), ", " | Inspected]}; - [First | ImproperRest] -> - {improper, [echo@inspect(First), " | ", echo@inspect(ImproperRest)]} - end. - -inspect@maybe_gleam_atom(Atom, PrevChar, Acc) -> - case {Atom, PrevChar} of - {<<>>, none} -> - {error, nil}; - {<>, none} when ?is_digit_char(First) -> - {error, nil}; - {<<"_", _/binary>>, none} -> - {error, nil}; - {<<"_">>, _} -> - {error, nil}; - {<<"_", _/binary>>, $_} -> - {error, nil}; - {<>, _} when not ?is_atom_char(First) -> - {error, nil}; - {<>, none} -> - inspect@maybe_gleam_atom(Rest, First, <>); - {<<"_", Rest/binary>>, _} -> - inspect@maybe_gleam_atom(Rest, $_, Acc); - {<>, $_} -> - inspect@maybe_gleam_atom(Rest, First, <>); - {<>, _} -> - inspect@maybe_gleam_atom(Rest, First, <>); - {<<>>, _} -> - {ok, Acc}; - _ -> - erlang:throw({gleam_error, echo, Atom, PrevChar, Acc}) - end. - -inspect@uppercase(X) -> X - 32. - diff --git a/test-output/cases/echo_function/build/dev/erlang/echo_custom_type/ebin/echo_custom_type.app b/test-output/cases/echo_function/build/dev/erlang/echo_custom_type/ebin/echo_custom_type.app deleted file mode 100644 index 88ffb4c34db..00000000000 --- a/test-output/cases/echo_function/build/dev/erlang/echo_custom_type/ebin/echo_custom_type.app +++ /dev/null @@ -1,7 +0,0 @@ -{application, echo_custom_type, [ - {vsn, "1.0.0"}, - {applications, []}, - {description, ""}, - {modules, [main]}, - {registered, []} -]}. diff --git a/test-output/cases/echo_function/build/dev/erlang/gleam_version b/test-output/cases/echo_function/build/dev/erlang/gleam_version deleted file mode 100644 index 3e1ad720b13..00000000000 --- a/test-output/cases/echo_function/build/dev/erlang/gleam_version +++ /dev/null @@ -1 +0,0 @@ -1.5.0 \ No newline at end of file diff --git a/test-output/cases/echo_function/build/dev/javascript/echo_custom_type/_gleam_artefacts/main.cache b/test-output/cases/echo_function/build/dev/javascript/echo_custom_type/_gleam_artefacts/main.cache deleted file mode 100644 index 6f5322b4619..00000000000 Binary files a/test-output/cases/echo_function/build/dev/javascript/echo_custom_type/_gleam_artefacts/main.cache and /dev/null differ diff --git a/test-output/cases/echo_function/build/dev/javascript/echo_custom_type/_gleam_artefacts/main.cache_meta b/test-output/cases/echo_function/build/dev/javascript/echo_custom_type/_gleam_artefacts/main.cache_meta deleted file mode 100644 index f2b9f5e0ed4..00000000000 Binary files a/test-output/cases/echo_function/build/dev/javascript/echo_custom_type/_gleam_artefacts/main.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_function/build/dev/javascript/echo_custom_type/_gleam_artefacts/main.cache_warnings b/test-output/cases/echo_function/build/dev/javascript/echo_custom_type/_gleam_artefacts/main.cache_warnings deleted file mode 100644 index 1b1cb4d44c5..00000000000 Binary files a/test-output/cases/echo_function/build/dev/javascript/echo_custom_type/_gleam_artefacts/main.cache_warnings and /dev/null differ diff --git a/test-output/cases/echo_function/build/dev/javascript/echo_custom_type/gleam.main.mjs b/test-output/cases/echo_function/build/dev/javascript/echo_custom_type/gleam.main.mjs deleted file mode 100644 index e230911e646..00000000000 --- a/test-output/cases/echo_function/build/dev/javascript/echo_custom_type/gleam.main.mjs +++ /dev/null @@ -1,2 +0,0 @@ -import { main } from "./main.mjs"; -main(); diff --git a/test-output/cases/echo_function/build/dev/javascript/echo_custom_type/gleam.mjs b/test-output/cases/echo_function/build/dev/javascript/echo_custom_type/gleam.mjs deleted file mode 100644 index 197cbbc35d4..00000000000 --- a/test-output/cases/echo_function/build/dev/javascript/echo_custom_type/gleam.mjs +++ /dev/null @@ -1 +0,0 @@ -export * from "../prelude.mjs"; diff --git a/test-output/cases/echo_function/build/dev/javascript/echo_custom_type/main.mjs b/test-output/cases/echo_function/build/dev/javascript/echo_custom_type/main.mjs deleted file mode 100644 index ee932e08d1d..00000000000 --- a/test-output/cases/echo_function/build/dev/javascript/echo_custom_type/main.mjs +++ /dev/null @@ -1,132 +0,0 @@ -import { - BitArray as $BitArray, - List as $List, - UtfCodepoint as $UtfCodepoint, - CustomType as $CustomType, -} from "./gleam.mjs"; - -function private$() { - return 1; -} - -export function main() { - echo((n) => { return n + 1; }, "src/main.gleam", 2); - return echo(private$, "src/main.gleam", 3); -} - -function echo(value, file, line) { - const grey = "\u001b[90m"; - const reset_color = "\u001b[39m"; - const file_line = `${file}:${line}`; - const string_value = echo$inspect(value); - - if (typeof process === "object" && process.stderr?.write) { - // If we're in Node.js, use `stderr` - const string = `${grey}${file_line}${reset_color}\n${string_value}\n`; - process.stderr.write(string); - } else if (typeof Deno === "object") { - // If we're in Deno, use `stderr` - const string = `${grey}${file_line}${reset_color}\n${string_value}\n`; - Deno.stderr.writeSync(new TextEncoder().encode(string)); - } else { - // Otherwise, use `console.log` - // The browser's console.log doesn't support ansi escape codes - const string = `${file_line}\n${string_value}`; - console.log(string); - } - - return value; -} - -function echo$inspectString(str) { - let new_str = '"'; - for (let i = 0; i < str.length; i++) { - let char = str[i]; - if (char == "\n") new_str += "\\n"; - else if (char == "\r") new_str += "\\r"; - else if (char == "\t") new_str += "\\t"; - else if (char == "\f") new_str += "\\f"; - else if (char == "\\") new_str += "\\\\"; - else if (char == '"') new_str += '\\"'; - else if (char < " " || (char > "~" && char < "\u{00A0}")) { - new_str += "\\u{" + char.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0") + "}"; - } else { - new_str += char; - } - } - new_str += '"'; - return new_str; -} - -function echo$inspectDict(map) { - let body = "dict.from_list(["; - let first = true; - map.forEach((value, key) => { - if (!first) body = body + ", "; - body = body + "#(" + echo$inspect(key) + ", " + echo$inspect(value) + ")"; - first = false; - }); - return body + "])"; -} - -function echo$inspectCustomType(record) { - const props = Object.keys(record) - .map((label) => { - const value = echo$inspect(record[label]); - return isNaN(parseInt(label)) ? `${label}: ${value}` : value; - }) - .join(", "); - return props ? `${record.constructor.name}(${props})` : record.constructor.name; -} - -function echo$inspectObject(v) { - const name = Object.getPrototypeOf(v)?.constructor?.name || "Object"; - const props = []; - for (const k of Object.keys(v)) { - props.push(`${echo$inspect(k)}: ${echo$inspect(v[k])}`); - } - const body = props.length ? " " + props.join(", ") + " " : ""; - const head = name === "Object" ? "" : name + " "; - return `//js(${head}{${body}})`; -} - -function echo$inspect(v) { - const t = typeof v; - if (v === true) return "True"; - if (v === false) return "False"; - if (v === null) return "//js(null)"; - if (v === undefined) return "Nil"; - if (t === "string") return echo$inspectString(v); - if (t === "bigint" || t === "number") return v.toString(); - if (Array.isArray(v)) return `#(${v.map(echo$inspect).join(", ")})`; - if (v instanceof $List) return `[${v.toArray().map(echo$inspect).join(", ")}]`; - if (v instanceof $UtfCodepoint) return `//utfcodepoint(${String.fromCodePoint(v.value)})`; - if (v instanceof $BitArray) return `<<${Array.from(v.buffer).join(", ")}>>`; - if (v instanceof $CustomType) return echo$inspectCustomType(v); - if (echo$isDict(v)) return echo$inspectDict(v); - if (v instanceof Set) return `//js(Set(${[...v].map(echo$inspect).join(", ")}))`; - if (v instanceof RegExp) return `//js(${v})`; - if (v instanceof Date) return `//js(Date("${v.toISOString()}"))`; - if (v instanceof Function) { - const args = []; - for (const i of Array(v.length).keys()) args.push(String.fromCharCode(i + 97)); - return `//fn(${args.join(", ")}) { ... }`; - } - return echo$inspectObject(v); -} - -function echo$isDict(value) { - try { - // We can only check if an object is a stdlib Dict if it is one of the - // project's dependencies. - // The `Dict` class is the default export of `stdlib/dict.mjs` - // that we import as `$stdlib$dict`. - return value instanceof $stdlib$dict.default; - } catch { - // If stdlib is not one of the project's dependencies then `$stdlib$dict` - // will not have been imported and the check will throw an exception meaning - // we can't check if something is actually a `Dict`. - return false; - } -} - diff --git a/test-output/cases/echo_function/build/dev/javascript/gleam_version b/test-output/cases/echo_function/build/dev/javascript/gleam_version deleted file mode 100644 index 3e1ad720b13..00000000000 --- a/test-output/cases/echo_function/build/dev/javascript/gleam_version +++ /dev/null @@ -1 +0,0 @@ -1.5.0 \ No newline at end of file diff --git a/test-output/cases/echo_function/build/dev/javascript/prelude.mjs b/test-output/cases/echo_function/build/dev/javascript/prelude.mjs deleted file mode 100644 index d2adeef273f..00000000000 --- a/test-output/cases/echo_function/build/dev/javascript/prelude.mjs +++ /dev/null @@ -1,455 +0,0 @@ -// Values marked with @internal are not part of the public API and may change -// without notice. - -export class CustomType { - withFields(fields) { - let properties = Object.keys(this).map((label) => - label in fields ? fields[label] : this[label], - ); - return new this.constructor(...properties); - } -} - -export class List { - static fromArray(array, tail) { - let t = tail || new Empty(); - for (let i = array.length - 1; i >= 0; --i) { - t = new NonEmpty(array[i], t); - } - return t; - } - - [Symbol.iterator]() { - return new ListIterator(this); - } - - toArray() { - return [...this]; - } - - // @internal - atLeastLength(desired) { - for (let _ of this) { - if (desired <= 0) return true; - desired--; - } - return desired <= 0; - } - - // @internal - hasLength(desired) { - for (let _ of this) { - if (desired <= 0) return false; - desired--; - } - return desired === 0; - } - - // @internal - countLength() { - let length = 0; - for (let _ of this) length++; - return length; - } -} - -// @internal -export function prepend(element, tail) { - return new NonEmpty(element, tail); -} - -export function toList(elements, tail) { - return List.fromArray(elements, tail); -} - -// @internal -class ListIterator { - #current; - - constructor(current) { - this.#current = current; - } - - next() { - if (this.#current instanceof Empty) { - return { done: true }; - } else { - let { head, tail } = this.#current; - this.#current = tail; - return { value: head, done: false }; - } - } -} - -export class Empty extends List {} - -export class NonEmpty extends List { - constructor(head, tail) { - super(); - this.head = head; - this.tail = tail; - } -} - -export class BitArray { - constructor(buffer) { - if (!(buffer instanceof Uint8Array)) { - throw "BitArray can only be constructed from a Uint8Array"; - } - this.buffer = buffer; - } - - // @internal - get length() { - return this.buffer.length; - } - - // @internal - byteAt(index) { - return this.buffer[index]; - } - - // @internal - floatFromSlice(start, end, isBigEndian) { - return byteArrayToFloat(this.buffer, start, end, isBigEndian); - } - - // @internal - intFromSlice(start, end, isBigEndian, isSigned) { - return byteArrayToInt(this.buffer, start, end, isBigEndian, isSigned); - } - - // @internal - binaryFromSlice(start, end) { - return new BitArray(this.buffer.slice(start, end)); - } - - // @internal - sliceAfter(index) { - return new BitArray(this.buffer.slice(index)); - } -} - -export class UtfCodepoint { - constructor(value) { - this.value = value; - } -} - -// @internal -export function toBitArray(segments) { - if (segments.length === 0) { - return new BitArray(new Uint8Array()); - } - - if (segments.length === 1) { - // When there is a single Uint8Array segment, pass it directly to the bit - // array constructor to avoid a copy - if (segments[0] instanceof Uint8Array) { - return new BitArray(segments[0]); - } - - return new BitArray(new Uint8Array(segments)); - } - - // Count the total number of bytes, and check if there are any Uint8Array - // segments - let bytes = 0; - let hasUint8ArraySegment = false; - for (const segment of segments) { - if (segment instanceof Uint8Array) { - bytes += segment.byteLength; - hasUint8ArraySegment = true; - } else { - bytes++; - } - } - - // If there aren't any Uint8Array segments then pass the segments array - // directly to the Uint8Array constructor - if (!hasUint8ArraySegment) { - return new BitArray(new Uint8Array(segments)); - } - - // Copy the segments into a Uint8Array - let u8Array = new Uint8Array(bytes); - let cursor = 0; - for (let segment of segments) { - if (segment instanceof Uint8Array) { - u8Array.set(segment, cursor); - cursor += segment.byteLength; - } else { - u8Array[cursor] = segment; - cursor++; - } - } - - return new BitArray(u8Array); -} - -// @internal -// Derived from this answer https://stackoverflow.com/questions/8482309/converting-javascript-integer-to-byte-array-and-back -export function sizedInt(value, size, isBigEndian) { - if (size < 0) { - return new Uint8Array(); - } - if (size % 8 != 0) { - const msg = `Bit arrays must be byte aligned on JavaScript, got size of ${size} bits`; - throw new globalThis.Error(msg); - } - - const byteArray = new Uint8Array(size / 8); - - // Convert negative number to two's complement representation - if (value < 0) { - value = 2 ** size + value; - } - - if (isBigEndian) { - for (let i = byteArray.length - 1; i >= 0; i--) { - const byte = value % 256; - byteArray[i] = byte; - value = (value - byte) / 256; - } - } else { - for (let i = 0; i < byteArray.length; i++) { - const byte = value % 256; - byteArray[i] = byte; - value = (value - byte) / 256; - } - } - - return byteArray; -} - -// @internal -export function byteArrayToInt(byteArray, start, end, isBigEndian, isSigned) { - let value = 0; - - // Read bytes as an unsigned integer value - if (isBigEndian) { - for (let i = start; i < end; i++) { - value = value * 256 + byteArray[i]; - } - } else { - for (let i = end - 1; i >= start; i--) { - value = value * 256 + byteArray[i]; - } - } - - if (isSigned) { - const byteSize = end - start; - - const highBit = 2 ** (byteSize * 8 - 1); - - // If the high bit is set and this is a signed integer, reinterpret as - // two's complement - if (value >= highBit) { - value -= highBit * 2; - } - } - - return value; -} - -// @internal -export function byteArrayToFloat(byteArray, start, end, isBigEndian) { - const view = new DataView(byteArray.buffer); - - const byteSize = end - start; - - if (byteSize === 8) { - return view.getFloat64(start, !isBigEndian); - } else if (byteSize === 4) { - return view.getFloat32(start, !isBigEndian); - } else { - const msg = `Sized floats must be 32-bit or 64-bit on JavaScript, got size of ${byteSize * 8} bits`; - throw new globalThis.Error(msg); - } -} - -// @internal -export function stringBits(string) { - return new TextEncoder().encode(string); -} - -// @internal -export function codepointBits(codepoint) { - return stringBits(String.fromCodePoint(codepoint.value)); -} - -// @internal -export function sizedFloat(float, size, isBigEndian) { - if (size !== 32 && size !== 64) { - const msg = `Sized floats must be 32-bit or 64-bit on JavaScript, got size of ${size} bits`; - throw new globalThis.Error(msg); - } - - const byteArray = new Uint8Array(size / 8); - - const view = new DataView(byteArray.buffer); - - if (size == 64) { - view.setFloat64(0, float, !isBigEndian); - } else if (size === 32) { - view.setFloat32(0, float, !isBigEndian); - } - - return byteArray; -} - -export class Result extends CustomType { - // @internal - static isResult(data) { - return data instanceof Result; - } -} - -export class Ok extends Result { - constructor(value) { - super(); - this[0] = value; - } - - // @internal - isOk() { - return true; - } -} - -export class Error extends Result { - constructor(detail) { - super(); - this[0] = detail; - } - - // @internal - isOk() { - return false; - } -} - -export function isEqual(x, y) { - let values = [x, y]; - - while (values.length) { - let a = values.pop(); - let b = values.pop(); - if (a === b) continue; - - if (!isObject(a) || !isObject(b)) return false; - let unequal = - !structurallyCompatibleObjects(a, b) || - unequalDates(a, b) || - unequalBuffers(a, b) || - unequalArrays(a, b) || - unequalMaps(a, b) || - unequalSets(a, b) || - unequalRegExps(a, b); - if (unequal) return false; - - const proto = Object.getPrototypeOf(a); - if (proto !== null && typeof proto.equals === "function") { - try { - if (a.equals(b)) continue; - else return false; - } catch {} - } - - let [keys, get] = getters(a); - for (let k of keys(a)) { - values.push(get(a, k), get(b, k)); - } - } - - return true; -} - -function getters(object) { - if (object instanceof Map) { - return [(x) => x.keys(), (x, y) => x.get(y)]; - } else { - let extra = object instanceof globalThis.Error ? ["message"] : []; - return [(x) => [...extra, ...Object.keys(x)], (x, y) => x[y]]; - } -} - -function unequalDates(a, b) { - return a instanceof Date && (a > b || a < b); -} - -function unequalBuffers(a, b) { - return ( - a.buffer instanceof ArrayBuffer && - a.BYTES_PER_ELEMENT && - !(a.byteLength === b.byteLength && a.every((n, i) => n === b[i])) - ); -} - -function unequalArrays(a, b) { - return Array.isArray(a) && a.length !== b.length; -} - -function unequalMaps(a, b) { - return a instanceof Map && a.size !== b.size; -} - -function unequalSets(a, b) { - return ( - a instanceof Set && (a.size != b.size || [...a].some((e) => !b.has(e))) - ); -} - -function unequalRegExps(a, b) { - return a instanceof RegExp && (a.source !== b.source || a.flags !== b.flags); -} - -function isObject(a) { - return typeof a === "object" && a !== null; -} - -function structurallyCompatibleObjects(a, b) { - if (typeof a !== "object" && typeof b !== "object" && (!a || !b)) - return false; - - let nonstructural = [Promise, WeakSet, WeakMap, Function]; - if (nonstructural.some((c) => a instanceof c)) return false; - - return a.constructor === b.constructor; -} - -// @internal -export function remainderInt(a, b) { - if (b === 0) { - return 0; - } else { - return a % b; - } -} - -// @internal -export function divideInt(a, b) { - return Math.trunc(divideFloat(a, b)); -} - -// @internal -export function divideFloat(a, b) { - if (b === 0) { - return 0; - } else { - return a / b; - } -} - -// @internal -export function makeError(variant, module, line, fn, message, extra) { - let error = new globalThis.Error(message); - error.gleam_error = variant; - error.module = module; - error.line = line; - error.function = fn; - // TODO: Remove this with Gleam v2.0.0 - error.fn = fn; - for (let k in extra) error[k] = extra[k]; - return error; -} diff --git a/test-output/cases/echo_function/build/packages/packages.toml b/test-output/cases/echo_function/build/packages/packages.toml deleted file mode 100644 index e74c18552bb..00000000000 --- a/test-output/cases/echo_function/build/packages/packages.toml +++ /dev/null @@ -1 +0,0 @@ -[packages] diff --git a/test-output/cases/echo_function/manifest.toml b/test-output/cases/echo_function/manifest.toml deleted file mode 100644 index c5d779a3f81..00000000000 --- a/test-output/cases/echo_function/manifest.toml +++ /dev/null @@ -1,7 +0,0 @@ -# This file was generated by Gleam -# You typically do not need to edit this file - -packages = [ -] - -[requirements] diff --git a/test-output/cases/echo_importing_module_named_inspect/build/dev/erlang/echo_importing_module_named_inspect/_gleam_artefacts/echo_importing_module_named_inspect@@main.erl b/test-output/cases/echo_importing_module_named_inspect/build/dev/erlang/echo_importing_module_named_inspect/_gleam_artefacts/echo_importing_module_named_inspect@@main.erl deleted file mode 100644 index d2528e9c518..00000000000 --- a/test-output/cases/echo_importing_module_named_inspect/build/dev/erlang/echo_importing_module_named_inspect/_gleam_artefacts/echo_importing_module_named_inspect@@main.erl +++ /dev/null @@ -1,99 +0,0 @@ --module('echo_importing_module_named_inspect@@main'). --export([run/1]). - --define(red, "\e[31;1m"). --define(grey, "\e[90m"). --define(reset_color, "\e[39m"). --define(reset_all, "\e[0m"). - -run(Module) -> - io:setopts(standard_io, [binary, {encoding, utf8}]), - io:setopts(standard_error, [{encoding, utf8}]), - process_flag(trap_exit, true), - Pid = spawn_link(fun() -> run_module(Module) end), - receive - {'EXIT', Pid, {Reason, StackTrace}} -> - print_error(exit, Reason, StackTrace), - init:stop(1) - end. - -run_module(Module) -> - try - {ok, _} = application:ensure_all_started('echo_importing_module_named_inspect'), - erlang:process_flag(trap_exit, false), - Module:main(), - erlang:halt(0) - catch - Class:Reason:StackTrace -> - print_error(Class, Reason, StackTrace), - init:stop(1) - end. - -print_error(Class, Error, Stacktrace) -> - Printed = [ - ?red, "runtime error", ?reset_color, ": ", error_class(Class, Error), ?reset_all, - "\n\n", - error_message(Error), - "\n\n", - error_details(Class, Error), - "stacktrace:\n", - [error_frame(Line) || Line <- refine_first(Error, Stacktrace)] - ], - io:format(standard_error, "~ts~n", [Printed]). - -refine_first(#{gleam_error := _, line := L}, [{M, F, A, [{file, Fi} | _]} | S]) -> - [{M, F, A, [{file, Fi}, {line, L}]} | S]; -refine_first(_, S) -> - S. - -error_class(_, #{gleam_error := panic}) -> "panic"; -error_class(_, #{gleam_error := todo}) -> "todo"; -error_class(_, #{gleam_error := let_assert}) -> "let assert"; -error_class(Class, _) -> ["Erlang ", atom_to_binary(Class)]. - -error_message(#{gleam_error := _, message := M}) -> - M; -error_message(undef) -> - <<"A function was called but it did not exist."/utf8 >>; -error_message({case_clause, _}) -> - <<"No pattern matched in an Erlang case expression."/utf8>>; -error_message({badmatch, _}) -> - <<"An Erlang assignment pattern did not match."/utf8>>; -error_message(function_clause) -> - <<"No Erlang function clause matched the arguments it was called with."/utf8>>; -error_message(_) -> - <<"An error occurred outside of Gleam."/utf8>>. - -error_details(_, #{gleam_error := let_assert, value := V}) -> - ["unmatched value:\n ", print_term(V), $\n, $\n]; -error_details(_, {case_clause, V}) -> - ["unmatched value:\n ", print_term(V), $\n, $\n]; -error_details(_, {badmatch, V}) -> - ["unmatched value:\n ", print_term(V), $\n, $\n]; -error_details(_, #{gleam_error := _}) -> - []; -error_details(error, function_clause) -> - []; -error_details(error, undef) -> - []; -error_details(C, E) -> - ["erlang:", atom_to_binary(C), $(, print_term(E), $), $\n, $\n]. - -print_term(T) -> - try - gleam@string:inspect(T) - catch - _:_ -> io_lib:format("~p", [T]) - end. - -error_frame({?MODULE, _, _, _}) -> []; -error_frame({erl_eval, _, _, _}) -> []; -error_frame({init, _, _, _}) -> []; -error_frame({M, F, _, O}) -> - M1 = string:replace(atom_to_binary(M), "@", "/", all), - [" ", M1, $., atom_to_binary(F), error_frame_end(O), $\n]. - -error_frame_end([{file, Fi}, {line, L} | _]) -> - [?grey, $\s, Fi, $:, integer_to_binary(L), ?reset_all]; -error_frame_end(_) -> - [?grey, " unknown source", ?reset_all]. \ No newline at end of file diff --git a/test-output/cases/echo_importing_module_named_inspect/build/dev/erlang/echo_importing_module_named_inspect/_gleam_artefacts/gleam@@compile.erl b/test-output/cases/echo_importing_module_named_inspect/build/dev/erlang/echo_importing_module_named_inspect/_gleam_artefacts/gleam@@compile.erl deleted file mode 100644 index 3e0a645b737..00000000000 --- a/test-output/cases/echo_importing_module_named_inspect/build/dev/erlang/echo_importing_module_named_inspect/_gleam_artefacts/gleam@@compile.erl +++ /dev/null @@ -1,163 +0,0 @@ -#!/usr/bin/env escript --mode(compile). - -% TODO: Don't concurrently print warnings and errors -% TODO: Some tests - -main(_) -> compile_package_loop(). - -compile_package_loop() -> - case file:read_line(standard_io) of - eof -> ok; - {ok, Line} -> - Chars = unicode:characters_to_list(Line), - {ok, Tokens, _} = erl_scan:string(Chars), - {ok, {Lib, Out, Modules}} = erl_parse:parse_term(Tokens), - case compile_package(Lib, Out, Modules) of - ok -> io:put_chars("gleam-compile-result-ok\n"); - err -> io:put_chars("gleam-compile-result-error\n") - end, - compile_package_loop() - end. - -compile_package(Lib, Out, Modules) -> - IsElixirModule = fun(Module) -> - filename:extension(Module) =:= ".ex" - end, - {ElixirModules, ErlangModules} = lists:partition(IsElixirModule, Modules), - ok = configure_logging(), - ok = add_lib_to_erlang_path(Lib), - ok = filelib:ensure_dir([Out, $/]), - {ErlangOk, _ErlangBeams} = compile_erlang(ErlangModules, Out), - {ElixirOk, _ElixirBeams} = case ErlangOk of - true -> compile_elixir(ElixirModules, Out); - false -> {false, []} - end, - ok = del_lib_from_erlang_path(Lib), - case ErlangOk and ElixirOk of - true -> ok; - false -> err - end. - -compile_erlang(Modules, Out) -> - Workers = start_compiler_workers(Out), - ok = producer_loop(Modules, Workers), - collect_results({true, []}). - -collect_results(Acc = {Result, Beams}) -> - receive - {compiled, Beam} -> collect_results({Result, [Beam | Beams]}); - failed -> collect_results({false, Beams}) - after 0 -> Acc - end. - -producer_loop([], 0) -> - ok; -producer_loop([], Workers) -> - receive - {work_please, _} -> producer_loop([], Workers - 1) - end; -producer_loop([Module | Modules], Workers) -> - receive - {work_please, Worker} -> - erlang:send(Worker, {module, Module}), - producer_loop(Modules, Workers) - end. - -start_compiler_workers(Out) -> - Parent = self(), - NumSchedulers = erlang:system_info(schedulers), - SpawnWorker = fun(_) -> - erlang:spawn_link(fun() -> worker_loop(Parent, Out) end) - end, - lists:foreach(SpawnWorker, lists:seq(1, NumSchedulers)), - NumSchedulers. - -worker_loop(Parent, Out) -> - Options = [report_errors, report_warnings, debug_info, {outdir, Out}], - erlang:send(Parent, {work_please, self()}), - receive - {module, Module} -> - log({compiling, Module}), - case compile:file(Module, Options) of - {ok, ModuleName} -> - Beam = filename:join(Out, ModuleName) ++ ".beam", - Message = {compiled, Beam}, - log(Message), - erlang:send(Parent, Message); - error -> - log({failed, Module}), - erlang:send(Parent, failed) - end, - worker_loop(Parent, Out) - end. - -compile_elixir(Modules, Out) -> - Error = [ - "The program elixir was not found. Is it installed?", - $\n, - "Documentation for installing Elixir can be viewed here:", - $\n, - "https://elixir-lang.org/install.html" - ], - case Modules of - [] -> {true, []}; - _ -> - log({starting, "compiler.app"}), - ok = application:start(compiler), - log({starting, "elixir.app"}), - case application:start(elixir) of - ok -> do_compile_elixir(Modules, Out); - _ -> - io:put_chars(standard_error, [Error, $\n]), - {false, []} - end - end. - -do_compile_elixir(Modules, Out) -> - ModuleBins = lists:map(fun(Module) -> - log({compiling, Module}), - list_to_binary(Module) - end, Modules), - OutBin = list_to_binary(Out), - Options = [{dest, OutBin}], - % Silence "redefining module" warnings. - % Compiled modules in the build directory are added to the code path. - % These warnings result from recompiling loaded modules. - % TODO: This line can likely be removed if/when the build directory is cleaned before every compilation. - 'Elixir.Code':compiler_options([{ignore_module_conflict, true}]), - case 'Elixir.Kernel.ParallelCompiler':compile_to_path(ModuleBins, OutBin, Options) of - {ok, ModuleAtoms, _} -> - ToBeam = fun(ModuleAtom) -> - Beam = filename:join(Out, atom_to_list(ModuleAtom)) ++ ".beam", - log({compiled, Beam}), - Beam - end, - {true, lists:map(ToBeam, ModuleAtoms)}; - {error, Errors, _} -> - % Log all filenames associated with modules that failed to compile. - % Note: The compiler prints compilation errors upon encountering them. - ErrorFiles = lists:usort([File || {File, _, _} <- Errors]), - Log = fun(File) -> - log({failed, binary_to_list(File)}) - end, - lists:foreach(Log, ErrorFiles), - {false, []}; - _ -> {false, []} - end. - -add_lib_to_erlang_path(Lib) -> - code:add_paths(filelib:wildcard([Lib, "/*/ebin"])). - -del_lib_from_erlang_path(Lib) -> - code:del_paths(filelib:wildcard([Lib, "/*/ebin"])). - -configure_logging() -> - Enabled = os:getenv("GLEAM_LOG") /= false, - persistent_term:put(gleam_logging_enabled, Enabled). - -log(Term) -> - case persistent_term:get(gleam_logging_enabled) of - true -> erlang:display(Term), ok; - false -> ok - end. diff --git a/test-output/cases/echo_importing_module_named_inspect/build/dev/erlang/echo_importing_module_named_inspect/_gleam_artefacts/inspect.cache b/test-output/cases/echo_importing_module_named_inspect/build/dev/erlang/echo_importing_module_named_inspect/_gleam_artefacts/inspect.cache deleted file mode 100644 index 5ce0c73432a..00000000000 Binary files a/test-output/cases/echo_importing_module_named_inspect/build/dev/erlang/echo_importing_module_named_inspect/_gleam_artefacts/inspect.cache and /dev/null differ diff --git a/test-output/cases/echo_importing_module_named_inspect/build/dev/erlang/echo_importing_module_named_inspect/_gleam_artefacts/inspect.cache_meta b/test-output/cases/echo_importing_module_named_inspect/build/dev/erlang/echo_importing_module_named_inspect/_gleam_artefacts/inspect.cache_meta deleted file mode 100644 index 425ffb22303..00000000000 Binary files a/test-output/cases/echo_importing_module_named_inspect/build/dev/erlang/echo_importing_module_named_inspect/_gleam_artefacts/inspect.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_importing_module_named_inspect/build/dev/erlang/echo_importing_module_named_inspect/_gleam_artefacts/inspect.cache_warnings b/test-output/cases/echo_importing_module_named_inspect/build/dev/erlang/echo_importing_module_named_inspect/_gleam_artefacts/inspect.cache_warnings deleted file mode 100644 index 1b1cb4d44c5..00000000000 Binary files a/test-output/cases/echo_importing_module_named_inspect/build/dev/erlang/echo_importing_module_named_inspect/_gleam_artefacts/inspect.cache_warnings and /dev/null differ diff --git a/test-output/cases/echo_importing_module_named_inspect/build/dev/erlang/echo_importing_module_named_inspect/_gleam_artefacts/inspect.erl b/test-output/cases/echo_importing_module_named_inspect/build/dev/erlang/echo_importing_module_named_inspect/_gleam_artefacts/inspect.erl deleted file mode 100644 index 085c90add0f..00000000000 --- a/test-output/cases/echo_importing_module_named_inspect/build/dev/erlang/echo_importing_module_named_inspect/_gleam_artefacts/inspect.erl +++ /dev/null @@ -1 +0,0 @@ --module(inspect). diff --git a/test-output/cases/echo_importing_module_named_inspect/build/dev/erlang/echo_importing_module_named_inspect/_gleam_artefacts/main.cache b/test-output/cases/echo_importing_module_named_inspect/build/dev/erlang/echo_importing_module_named_inspect/_gleam_artefacts/main.cache deleted file mode 100644 index 9f51f383758..00000000000 Binary files a/test-output/cases/echo_importing_module_named_inspect/build/dev/erlang/echo_importing_module_named_inspect/_gleam_artefacts/main.cache and /dev/null differ diff --git a/test-output/cases/echo_importing_module_named_inspect/build/dev/erlang/echo_importing_module_named_inspect/_gleam_artefacts/main.cache_meta b/test-output/cases/echo_importing_module_named_inspect/build/dev/erlang/echo_importing_module_named_inspect/_gleam_artefacts/main.cache_meta deleted file mode 100644 index ccd757cf556..00000000000 Binary files a/test-output/cases/echo_importing_module_named_inspect/build/dev/erlang/echo_importing_module_named_inspect/_gleam_artefacts/main.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_importing_module_named_inspect/build/dev/erlang/echo_importing_module_named_inspect/_gleam_artefacts/main.cache_warnings b/test-output/cases/echo_importing_module_named_inspect/build/dev/erlang/echo_importing_module_named_inspect/_gleam_artefacts/main.cache_warnings deleted file mode 100644 index 1b1cb4d44c5..00000000000 Binary files a/test-output/cases/echo_importing_module_named_inspect/build/dev/erlang/echo_importing_module_named_inspect/_gleam_artefacts/main.cache_warnings and /dev/null differ diff --git a/test-output/cases/echo_importing_module_named_inspect/build/dev/erlang/echo_importing_module_named_inspect/_gleam_artefacts/main.erl b/test-output/cases/echo_importing_module_named_inspect/build/dev/erlang/echo_importing_module_named_inspect/_gleam_artefacts/main.erl deleted file mode 100644 index e09b0182922..00000000000 --- a/test-output/cases/echo_importing_module_named_inspect/build/dev/erlang/echo_importing_module_named_inspect/_gleam_artefacts/main.erl +++ /dev/null @@ -1,189 +0,0 @@ --module(main). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([main/0]). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_importing_module_named_inspect/src/main.gleam", 3). --spec main() -> nil. -main() -> - echo(nil, "src/main.gleam", 4). - --define(is_lowercase_char(X), (X > 96 andalso X < 123)). --define(is_underscore_char(X), (X == 95)). --define(is_digit_char(X), (X > 47 andalso X < 58)). --define(could_be_record(Tuple), - erlang:is_tuple(Tuple) andalso - erlang:is_atom(erlang:element(1, Tuple)) andalso - erlang:element(1, Tuple) =/= false andalso - erlang:element(1, Tuple) =/= true andalso - erlang:element(1, Tuple) =/= nil -). --define(is_atom_char(C), - (?is_lowercase_char(C) orelse - ?is_underscore_char(C) orelse - ?is_digit_char(C)) -). - --define(grey, "\e[90m"). --define(reset_color, "\e[39m"). - -echo(Value, File, Line) -> - StringLine = erlang:integer_to_list(Line), - StringValue = echo@inspect(Value), - io:put_chars( - standard_error, - [?grey, File, $:, StringLine, ?reset_color, $\n, StringValue, $\n] - ), - Value. - -echo@inspect(Value) -> - case Value of - nil -> "Nil"; - true -> "True"; - false -> "False"; - Int when erlang:is_integer(Int) -> erlang:integer_to_list(Int); - Float when erlang:is_float(Float) -> io_lib_format:fwrite_g(Float); - Binary when erlang:is_binary(Binary) -> inspect@binary(Binary); - Bits when erlang:is_bitstring(Bits) -> inspect@bit_array(Bits); - Atom when erlang:is_atom(Atom) -> inspect@atom(Atom); - List when erlang:is_list(List) -> inspect@list(List); - Map when erlang:is_map(Map) -> inspect@map(Map); - Record when ?could_be_record(Record) -> inspect@record(Record); - Tuple when erlang:is_tuple(Tuple) -> inspect@tuple(Tuple); - Function when erlang:is_function(Function) -> inspect@function(Function); - Any -> ["//erl(", io_lib:format("~p", [Any]), ")"] - end. - -inspect@bit_array(Bits) -> - Pieces = inspect@bit_array_pieces(Bits, []), - Inner = lists:join(", ", lists:reverse(Pieces)), - ["<<", Inner, ">>"]. - -inspect@bit_array_pieces(Bits, Acc) -> - case Bits of - <<>> -> - Acc; - <> -> - inspect@bit_array_pieces(Rest, [erlang:integer_to_binary(Byte) | Acc]); - _ -> - Size = erlang:bit_size(Bits), - <> = Bits, - SizeString = [":size(", erlang:integer_to_binary(Size), ")"], - Piece = [erlang:integer_to_binary(RemainingBits), SizeString], - [Piece | Acc] - end. - -inspect@binary(Binary) -> - case inspect@maybe_utf8_string(Binary, <<>>) of - {ok, InspectedUtf8String} -> - InspectedUtf8String; - {error, not_a_utf8_string} -> - Segments = [erlang:integer_to_list(X) || <> <= Binary], - ["<<", lists:join(", ", Segments), ">>"] - end. - -inspect@atom(Atom) -> - Binary = erlang:atom_to_binary(Atom), - case inspect@maybe_gleam_atom(Binary, none, <<>>) of - {ok, Inspected} -> Inspected; - {error, _} -> ["atom.create_from_string(\"", Binary, "\")"] - end. - -inspect@list(List) -> - case inspect@proper_or_improper_list(List) of - {proper, Elements} -> ["[", Elements, "]"]; - {improper, Elements} -> ["//erl([", Elements, "])"] - end. - -inspect@map(Map) -> - Fields = [ - [<<"#(">>, echo@inspect(Key), <<", ">>, echo@inspect(Value), <<")">>] - || {Key, Value} <- maps:to_list(Map) - ], - ["dict.from_list([", lists:join(", ", Fields), "])"]. - -inspect@record(Record) -> - [Atom | ArgsList] = erlang:tuple_to_list(Record), - Args = lists:join(", ", lists:map(fun echo@inspect/1, ArgsList)), - [echo@inspect(Atom), "(", Args, ")"]. - -inspect@tuple(Tuple) -> - Elements = lists:map(fun echo@inspect/1, erlang:tuple_to_list(Tuple)), - ["#(", lists:join(", ", Elements), ")"]. - -inspect@function(Function) -> - {arity, Arity} = erlang:fun_info(Function, arity), - ArgsAsciiCodes = lists:seq($a, $a + Arity - 1), - Args = lists:join(", ", lists:map(fun(Arg) -> <> end, ArgsAsciiCodes)), - ["//fn(", Args, ") { ... }"]. - -inspect@maybe_utf8_string(Binary, Acc) -> - case Binary of - <<>> -> - {ok, <<$", Acc/binary, $">>}; - <> -> - Escaped = inspect@escape_grapheme(First), - inspect@maybe_utf8_string(Rest, <>); - _ -> - {error, not_a_utf8_string} - end. - -inspect@escape_grapheme(Char) -> - case Char of - $" -> <<$\\, $">>; - $\\ -> <<$\\, $\\>>; - $\r -> <<$\\, $r>>; - $\n -> <<$\\, $n>>; - $\t -> <<$\\, $t>>; - $\f -> <<$\\, $f>>; - X when X > 126, X < 160 -> inspect@convert_to_u(X); - X when X < 32 -> inspect@convert_to_u(X); - Other -> <> - end. - -inspect@convert_to_u(Code) -> - erlang:list_to_binary(io_lib:format("\\u{~4.16.0B}", [Code])). - -inspect@proper_or_improper_list(List) -> - case List of - [] -> - {proper, []}; - [First] -> - {proper, [echo@inspect(First)]}; - [First | Rest] when erlang:is_list(Rest) -> - {Kind, Inspected} = inspect@proper_or_improper_list(Rest), - {Kind, [echo@inspect(First), ", " | Inspected]}; - [First | ImproperRest] -> - {improper, [echo@inspect(First), " | ", echo@inspect(ImproperRest)]} - end. - -inspect@maybe_gleam_atom(Atom, PrevChar, Acc) -> - case {Atom, PrevChar} of - {<<>>, none} -> - {error, nil}; - {<>, none} when ?is_digit_char(First) -> - {error, nil}; - {<<"_", _/binary>>, none} -> - {error, nil}; - {<<"_">>, _} -> - {error, nil}; - {<<"_", _/binary>>, $_} -> - {error, nil}; - {<>, _} when not ?is_atom_char(First) -> - {error, nil}; - {<>, none} -> - inspect@maybe_gleam_atom(Rest, First, <>); - {<<"_", Rest/binary>>, _} -> - inspect@maybe_gleam_atom(Rest, $_, Acc); - {<>, $_} -> - inspect@maybe_gleam_atom(Rest, First, <>); - {<>, _} -> - inspect@maybe_gleam_atom(Rest, First, <>); - {<<>>, _} -> - {ok, Acc}; - _ -> - erlang:throw({gleam_error, echo, Atom, PrevChar, Acc}) - end. - -inspect@uppercase(X) -> X - 32. - diff --git a/test-output/cases/echo_importing_module_named_inspect/build/dev/erlang/echo_importing_module_named_inspect/ebin/echo_importing_module_named_inspect.app b/test-output/cases/echo_importing_module_named_inspect/build/dev/erlang/echo_importing_module_named_inspect/ebin/echo_importing_module_named_inspect.app deleted file mode 100644 index 3bad4ed89ab..00000000000 --- a/test-output/cases/echo_importing_module_named_inspect/build/dev/erlang/echo_importing_module_named_inspect/ebin/echo_importing_module_named_inspect.app +++ /dev/null @@ -1,8 +0,0 @@ -{application, echo_importing_module_named_inspect, [ - {vsn, "1.0.0"}, - {applications, []}, - {description, ""}, - {modules, [inspect, - main]}, - {registered, []} -]}. diff --git a/test-output/cases/echo_importing_module_named_inspect/build/dev/erlang/gleam_version b/test-output/cases/echo_importing_module_named_inspect/build/dev/erlang/gleam_version deleted file mode 100644 index 3e1ad720b13..00000000000 --- a/test-output/cases/echo_importing_module_named_inspect/build/dev/erlang/gleam_version +++ /dev/null @@ -1 +0,0 @@ -1.5.0 \ No newline at end of file diff --git a/test-output/cases/echo_importing_module_named_inspect/build/dev/javascript/echo_importing_module_named_inspect/_gleam_artefacts/inspect.cache b/test-output/cases/echo_importing_module_named_inspect/build/dev/javascript/echo_importing_module_named_inspect/_gleam_artefacts/inspect.cache deleted file mode 100644 index 40aad4342e7..00000000000 Binary files a/test-output/cases/echo_importing_module_named_inspect/build/dev/javascript/echo_importing_module_named_inspect/_gleam_artefacts/inspect.cache and /dev/null differ diff --git a/test-output/cases/echo_importing_module_named_inspect/build/dev/javascript/echo_importing_module_named_inspect/_gleam_artefacts/inspect.cache_meta b/test-output/cases/echo_importing_module_named_inspect/build/dev/javascript/echo_importing_module_named_inspect/_gleam_artefacts/inspect.cache_meta deleted file mode 100644 index 425ffb22303..00000000000 Binary files a/test-output/cases/echo_importing_module_named_inspect/build/dev/javascript/echo_importing_module_named_inspect/_gleam_artefacts/inspect.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_importing_module_named_inspect/build/dev/javascript/echo_importing_module_named_inspect/_gleam_artefacts/inspect.cache_warnings b/test-output/cases/echo_importing_module_named_inspect/build/dev/javascript/echo_importing_module_named_inspect/_gleam_artefacts/inspect.cache_warnings deleted file mode 100644 index 1b1cb4d44c5..00000000000 Binary files a/test-output/cases/echo_importing_module_named_inspect/build/dev/javascript/echo_importing_module_named_inspect/_gleam_artefacts/inspect.cache_warnings and /dev/null differ diff --git a/test-output/cases/echo_importing_module_named_inspect/build/dev/javascript/echo_importing_module_named_inspect/_gleam_artefacts/main.cache b/test-output/cases/echo_importing_module_named_inspect/build/dev/javascript/echo_importing_module_named_inspect/_gleam_artefacts/main.cache deleted file mode 100644 index e6d2c2710d0..00000000000 Binary files a/test-output/cases/echo_importing_module_named_inspect/build/dev/javascript/echo_importing_module_named_inspect/_gleam_artefacts/main.cache and /dev/null differ diff --git a/test-output/cases/echo_importing_module_named_inspect/build/dev/javascript/echo_importing_module_named_inspect/_gleam_artefacts/main.cache_meta b/test-output/cases/echo_importing_module_named_inspect/build/dev/javascript/echo_importing_module_named_inspect/_gleam_artefacts/main.cache_meta deleted file mode 100644 index ccd757cf556..00000000000 Binary files a/test-output/cases/echo_importing_module_named_inspect/build/dev/javascript/echo_importing_module_named_inspect/_gleam_artefacts/main.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_importing_module_named_inspect/build/dev/javascript/echo_importing_module_named_inspect/_gleam_artefacts/main.cache_warnings b/test-output/cases/echo_importing_module_named_inspect/build/dev/javascript/echo_importing_module_named_inspect/_gleam_artefacts/main.cache_warnings deleted file mode 100644 index 1b1cb4d44c5..00000000000 Binary files a/test-output/cases/echo_importing_module_named_inspect/build/dev/javascript/echo_importing_module_named_inspect/_gleam_artefacts/main.cache_warnings and /dev/null differ diff --git a/test-output/cases/echo_importing_module_named_inspect/build/dev/javascript/echo_importing_module_named_inspect/gleam.main.mjs b/test-output/cases/echo_importing_module_named_inspect/build/dev/javascript/echo_importing_module_named_inspect/gleam.main.mjs deleted file mode 100644 index e230911e646..00000000000 --- a/test-output/cases/echo_importing_module_named_inspect/build/dev/javascript/echo_importing_module_named_inspect/gleam.main.mjs +++ /dev/null @@ -1,2 +0,0 @@ -import { main } from "./main.mjs"; -main(); diff --git a/test-output/cases/echo_importing_module_named_inspect/build/dev/javascript/echo_importing_module_named_inspect/gleam.mjs b/test-output/cases/echo_importing_module_named_inspect/build/dev/javascript/echo_importing_module_named_inspect/gleam.mjs deleted file mode 100644 index 197cbbc35d4..00000000000 --- a/test-output/cases/echo_importing_module_named_inspect/build/dev/javascript/echo_importing_module_named_inspect/gleam.mjs +++ /dev/null @@ -1 +0,0 @@ -export * from "../prelude.mjs"; diff --git a/test-output/cases/echo_importing_module_named_inspect/build/dev/javascript/echo_importing_module_named_inspect/inspect.mjs b/test-output/cases/echo_importing_module_named_inspect/build/dev/javascript/echo_importing_module_named_inspect/inspect.mjs deleted file mode 100644 index 3aa88ca8633..00000000000 --- a/test-output/cases/echo_importing_module_named_inspect/build/dev/javascript/echo_importing_module_named_inspect/inspect.mjs +++ /dev/null @@ -1 +0,0 @@ -export const x = undefined; diff --git a/test-output/cases/echo_importing_module_named_inspect/build/dev/javascript/echo_importing_module_named_inspect/main.mjs b/test-output/cases/echo_importing_module_named_inspect/build/dev/javascript/echo_importing_module_named_inspect/main.mjs deleted file mode 100644 index 28fdc13a9b0..00000000000 --- a/test-output/cases/echo_importing_module_named_inspect/build/dev/javascript/echo_importing_module_named_inspect/main.mjs +++ /dev/null @@ -1,128 +0,0 @@ -import { - BitArray as $BitArray, - List as $List, - UtfCodepoint as $UtfCodepoint, - CustomType as $CustomType, -} from "./gleam.mjs"; -import * as $inspect from "./inspect.mjs"; - -export function main() { - return echo($inspect.x, "src/main.gleam", 4); -} - -function echo(value, file, line) { - const grey = "\u001b[90m"; - const reset_color = "\u001b[39m"; - const file_line = `${file}:${line}`; - const string_value = echo$inspect(value); - - if (typeof process === "object" && process.stderr?.write) { - // If we're in Node.js, use `stderr` - const string = `${grey}${file_line}${reset_color}\n${string_value}\n`; - process.stderr.write(string); - } else if (typeof Deno === "object") { - // If we're in Deno, use `stderr` - const string = `${grey}${file_line}${reset_color}\n${string_value}\n`; - Deno.stderr.writeSync(new TextEncoder().encode(string)); - } else { - // Otherwise, use `console.log` - // The browser's console.log doesn't support ansi escape codes - const string = `${file_line}\n${string_value}`; - console.log(string); - } - - return value; -} - -function echo$inspectString(str) { - let new_str = '"'; - for (let i = 0; i < str.length; i++) { - let char = str[i]; - if (char == "\n") new_str += "\\n"; - else if (char == "\r") new_str += "\\r"; - else if (char == "\t") new_str += "\\t"; - else if (char == "\f") new_str += "\\f"; - else if (char == "\\") new_str += "\\\\"; - else if (char == '"') new_str += '\\"'; - else if (char < " " || (char > "~" && char < "\u{00A0}")) { - new_str += "\\u{" + char.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0") + "}"; - } else { - new_str += char; - } - } - new_str += '"'; - return new_str; -} - -function echo$inspectDict(map) { - let body = "dict.from_list(["; - let first = true; - map.forEach((value, key) => { - if (!first) body = body + ", "; - body = body + "#(" + echo$inspect(key) + ", " + echo$inspect(value) + ")"; - first = false; - }); - return body + "])"; -} - -function echo$inspectCustomType(record) { - const props = Object.keys(record) - .map((label) => { - const value = echo$inspect(record[label]); - return isNaN(parseInt(label)) ? `${label}: ${value}` : value; - }) - .join(", "); - return props ? `${record.constructor.name}(${props})` : record.constructor.name; -} - -function echo$inspectObject(v) { - const name = Object.getPrototypeOf(v)?.constructor?.name || "Object"; - const props = []; - for (const k of Object.keys(v)) { - props.push(`${echo$inspect(k)}: ${echo$inspect(v[k])}`); - } - const body = props.length ? " " + props.join(", ") + " " : ""; - const head = name === "Object" ? "" : name + " "; - return `//js(${head}{${body}})`; -} - -function echo$inspect(v) { - const t = typeof v; - if (v === true) return "True"; - if (v === false) return "False"; - if (v === null) return "//js(null)"; - if (v === undefined) return "Nil"; - if (t === "string") return echo$inspectString(v); - if (t === "bigint" || t === "number") return v.toString(); - if (Array.isArray(v)) return `#(${v.map(echo$inspect).join(", ")})`; - if (v instanceof $List) return `[${v.toArray().map(echo$inspect).join(", ")}]`; - if (v instanceof $UtfCodepoint) return `//utfcodepoint(${String.fromCodePoint(v.value)})`; - if (v instanceof $BitArray) return `<<${Array.from(v.buffer).join(", ")}>>`; - if (v instanceof $CustomType) return echo$inspectCustomType(v); - if (echo$isDict(v)) return echo$inspectDict(v); - if (v instanceof Set) return `//js(Set(${[...v].map(echo$inspect).join(", ")}))`; - if (v instanceof RegExp) return `//js(${v})`; - if (v instanceof Date) return `//js(Date("${v.toISOString()}"))`; - if (v instanceof Function) { - const args = []; - for (const i of Array(v.length).keys()) args.push(String.fromCharCode(i + 97)); - return `//fn(${args.join(", ")}) { ... }`; - } - return echo$inspectObject(v); -} - -function echo$isDict(value) { - try { - // We can only check if an object is a stdlib Dict if it is one of the - // project's dependencies. - // The `Dict` class is the default export of `stdlib/dict.mjs` - // that we import as `$stdlib$dict`. - return value instanceof $stdlib$dict.default; - } catch { - // If stdlib is not one of the project's dependencies then `$stdlib$dict` - // will not have been imported and the check will throw an exception meaning - // we can't check if something is actually a `Dict`. - return false; - } -} - diff --git a/test-output/cases/echo_importing_module_named_inspect/build/dev/javascript/gleam_version b/test-output/cases/echo_importing_module_named_inspect/build/dev/javascript/gleam_version deleted file mode 100644 index 3e1ad720b13..00000000000 --- a/test-output/cases/echo_importing_module_named_inspect/build/dev/javascript/gleam_version +++ /dev/null @@ -1 +0,0 @@ -1.5.0 \ No newline at end of file diff --git a/test-output/cases/echo_importing_module_named_inspect/build/dev/javascript/prelude.mjs b/test-output/cases/echo_importing_module_named_inspect/build/dev/javascript/prelude.mjs deleted file mode 100644 index d2adeef273f..00000000000 --- a/test-output/cases/echo_importing_module_named_inspect/build/dev/javascript/prelude.mjs +++ /dev/null @@ -1,455 +0,0 @@ -// Values marked with @internal are not part of the public API and may change -// without notice. - -export class CustomType { - withFields(fields) { - let properties = Object.keys(this).map((label) => - label in fields ? fields[label] : this[label], - ); - return new this.constructor(...properties); - } -} - -export class List { - static fromArray(array, tail) { - let t = tail || new Empty(); - for (let i = array.length - 1; i >= 0; --i) { - t = new NonEmpty(array[i], t); - } - return t; - } - - [Symbol.iterator]() { - return new ListIterator(this); - } - - toArray() { - return [...this]; - } - - // @internal - atLeastLength(desired) { - for (let _ of this) { - if (desired <= 0) return true; - desired--; - } - return desired <= 0; - } - - // @internal - hasLength(desired) { - for (let _ of this) { - if (desired <= 0) return false; - desired--; - } - return desired === 0; - } - - // @internal - countLength() { - let length = 0; - for (let _ of this) length++; - return length; - } -} - -// @internal -export function prepend(element, tail) { - return new NonEmpty(element, tail); -} - -export function toList(elements, tail) { - return List.fromArray(elements, tail); -} - -// @internal -class ListIterator { - #current; - - constructor(current) { - this.#current = current; - } - - next() { - if (this.#current instanceof Empty) { - return { done: true }; - } else { - let { head, tail } = this.#current; - this.#current = tail; - return { value: head, done: false }; - } - } -} - -export class Empty extends List {} - -export class NonEmpty extends List { - constructor(head, tail) { - super(); - this.head = head; - this.tail = tail; - } -} - -export class BitArray { - constructor(buffer) { - if (!(buffer instanceof Uint8Array)) { - throw "BitArray can only be constructed from a Uint8Array"; - } - this.buffer = buffer; - } - - // @internal - get length() { - return this.buffer.length; - } - - // @internal - byteAt(index) { - return this.buffer[index]; - } - - // @internal - floatFromSlice(start, end, isBigEndian) { - return byteArrayToFloat(this.buffer, start, end, isBigEndian); - } - - // @internal - intFromSlice(start, end, isBigEndian, isSigned) { - return byteArrayToInt(this.buffer, start, end, isBigEndian, isSigned); - } - - // @internal - binaryFromSlice(start, end) { - return new BitArray(this.buffer.slice(start, end)); - } - - // @internal - sliceAfter(index) { - return new BitArray(this.buffer.slice(index)); - } -} - -export class UtfCodepoint { - constructor(value) { - this.value = value; - } -} - -// @internal -export function toBitArray(segments) { - if (segments.length === 0) { - return new BitArray(new Uint8Array()); - } - - if (segments.length === 1) { - // When there is a single Uint8Array segment, pass it directly to the bit - // array constructor to avoid a copy - if (segments[0] instanceof Uint8Array) { - return new BitArray(segments[0]); - } - - return new BitArray(new Uint8Array(segments)); - } - - // Count the total number of bytes, and check if there are any Uint8Array - // segments - let bytes = 0; - let hasUint8ArraySegment = false; - for (const segment of segments) { - if (segment instanceof Uint8Array) { - bytes += segment.byteLength; - hasUint8ArraySegment = true; - } else { - bytes++; - } - } - - // If there aren't any Uint8Array segments then pass the segments array - // directly to the Uint8Array constructor - if (!hasUint8ArraySegment) { - return new BitArray(new Uint8Array(segments)); - } - - // Copy the segments into a Uint8Array - let u8Array = new Uint8Array(bytes); - let cursor = 0; - for (let segment of segments) { - if (segment instanceof Uint8Array) { - u8Array.set(segment, cursor); - cursor += segment.byteLength; - } else { - u8Array[cursor] = segment; - cursor++; - } - } - - return new BitArray(u8Array); -} - -// @internal -// Derived from this answer https://stackoverflow.com/questions/8482309/converting-javascript-integer-to-byte-array-and-back -export function sizedInt(value, size, isBigEndian) { - if (size < 0) { - return new Uint8Array(); - } - if (size % 8 != 0) { - const msg = `Bit arrays must be byte aligned on JavaScript, got size of ${size} bits`; - throw new globalThis.Error(msg); - } - - const byteArray = new Uint8Array(size / 8); - - // Convert negative number to two's complement representation - if (value < 0) { - value = 2 ** size + value; - } - - if (isBigEndian) { - for (let i = byteArray.length - 1; i >= 0; i--) { - const byte = value % 256; - byteArray[i] = byte; - value = (value - byte) / 256; - } - } else { - for (let i = 0; i < byteArray.length; i++) { - const byte = value % 256; - byteArray[i] = byte; - value = (value - byte) / 256; - } - } - - return byteArray; -} - -// @internal -export function byteArrayToInt(byteArray, start, end, isBigEndian, isSigned) { - let value = 0; - - // Read bytes as an unsigned integer value - if (isBigEndian) { - for (let i = start; i < end; i++) { - value = value * 256 + byteArray[i]; - } - } else { - for (let i = end - 1; i >= start; i--) { - value = value * 256 + byteArray[i]; - } - } - - if (isSigned) { - const byteSize = end - start; - - const highBit = 2 ** (byteSize * 8 - 1); - - // If the high bit is set and this is a signed integer, reinterpret as - // two's complement - if (value >= highBit) { - value -= highBit * 2; - } - } - - return value; -} - -// @internal -export function byteArrayToFloat(byteArray, start, end, isBigEndian) { - const view = new DataView(byteArray.buffer); - - const byteSize = end - start; - - if (byteSize === 8) { - return view.getFloat64(start, !isBigEndian); - } else if (byteSize === 4) { - return view.getFloat32(start, !isBigEndian); - } else { - const msg = `Sized floats must be 32-bit or 64-bit on JavaScript, got size of ${byteSize * 8} bits`; - throw new globalThis.Error(msg); - } -} - -// @internal -export function stringBits(string) { - return new TextEncoder().encode(string); -} - -// @internal -export function codepointBits(codepoint) { - return stringBits(String.fromCodePoint(codepoint.value)); -} - -// @internal -export function sizedFloat(float, size, isBigEndian) { - if (size !== 32 && size !== 64) { - const msg = `Sized floats must be 32-bit or 64-bit on JavaScript, got size of ${size} bits`; - throw new globalThis.Error(msg); - } - - const byteArray = new Uint8Array(size / 8); - - const view = new DataView(byteArray.buffer); - - if (size == 64) { - view.setFloat64(0, float, !isBigEndian); - } else if (size === 32) { - view.setFloat32(0, float, !isBigEndian); - } - - return byteArray; -} - -export class Result extends CustomType { - // @internal - static isResult(data) { - return data instanceof Result; - } -} - -export class Ok extends Result { - constructor(value) { - super(); - this[0] = value; - } - - // @internal - isOk() { - return true; - } -} - -export class Error extends Result { - constructor(detail) { - super(); - this[0] = detail; - } - - // @internal - isOk() { - return false; - } -} - -export function isEqual(x, y) { - let values = [x, y]; - - while (values.length) { - let a = values.pop(); - let b = values.pop(); - if (a === b) continue; - - if (!isObject(a) || !isObject(b)) return false; - let unequal = - !structurallyCompatibleObjects(a, b) || - unequalDates(a, b) || - unequalBuffers(a, b) || - unequalArrays(a, b) || - unequalMaps(a, b) || - unequalSets(a, b) || - unequalRegExps(a, b); - if (unequal) return false; - - const proto = Object.getPrototypeOf(a); - if (proto !== null && typeof proto.equals === "function") { - try { - if (a.equals(b)) continue; - else return false; - } catch {} - } - - let [keys, get] = getters(a); - for (let k of keys(a)) { - values.push(get(a, k), get(b, k)); - } - } - - return true; -} - -function getters(object) { - if (object instanceof Map) { - return [(x) => x.keys(), (x, y) => x.get(y)]; - } else { - let extra = object instanceof globalThis.Error ? ["message"] : []; - return [(x) => [...extra, ...Object.keys(x)], (x, y) => x[y]]; - } -} - -function unequalDates(a, b) { - return a instanceof Date && (a > b || a < b); -} - -function unequalBuffers(a, b) { - return ( - a.buffer instanceof ArrayBuffer && - a.BYTES_PER_ELEMENT && - !(a.byteLength === b.byteLength && a.every((n, i) => n === b[i])) - ); -} - -function unequalArrays(a, b) { - return Array.isArray(a) && a.length !== b.length; -} - -function unequalMaps(a, b) { - return a instanceof Map && a.size !== b.size; -} - -function unequalSets(a, b) { - return ( - a instanceof Set && (a.size != b.size || [...a].some((e) => !b.has(e))) - ); -} - -function unequalRegExps(a, b) { - return a instanceof RegExp && (a.source !== b.source || a.flags !== b.flags); -} - -function isObject(a) { - return typeof a === "object" && a !== null; -} - -function structurallyCompatibleObjects(a, b) { - if (typeof a !== "object" && typeof b !== "object" && (!a || !b)) - return false; - - let nonstructural = [Promise, WeakSet, WeakMap, Function]; - if (nonstructural.some((c) => a instanceof c)) return false; - - return a.constructor === b.constructor; -} - -// @internal -export function remainderInt(a, b) { - if (b === 0) { - return 0; - } else { - return a % b; - } -} - -// @internal -export function divideInt(a, b) { - return Math.trunc(divideFloat(a, b)); -} - -// @internal -export function divideFloat(a, b) { - if (b === 0) { - return 0; - } else { - return a / b; - } -} - -// @internal -export function makeError(variant, module, line, fn, message, extra) { - let error = new globalThis.Error(message); - error.gleam_error = variant; - error.module = module; - error.line = line; - error.function = fn; - // TODO: Remove this with Gleam v2.0.0 - error.fn = fn; - for (let k in extra) error[k] = extra[k]; - return error; -} diff --git a/test-output/cases/echo_importing_module_named_inspect/build/packages/packages.toml b/test-output/cases/echo_importing_module_named_inspect/build/packages/packages.toml deleted file mode 100644 index e74c18552bb..00000000000 --- a/test-output/cases/echo_importing_module_named_inspect/build/packages/packages.toml +++ /dev/null @@ -1 +0,0 @@ -[packages] diff --git a/test-output/cases/echo_importing_module_named_inspect/manifest.toml b/test-output/cases/echo_importing_module_named_inspect/manifest.toml deleted file mode 100644 index c5d779a3f81..00000000000 --- a/test-output/cases/echo_importing_module_named_inspect/manifest.toml +++ /dev/null @@ -1,7 +0,0 @@ -# This file was generated by Gleam -# You typically do not need to edit this file - -packages = [ -] - -[requirements] diff --git a/test-output/cases/echo_int/build/dev/erlang/echo_int/_gleam_artefacts/echo_int@@main.erl b/test-output/cases/echo_int/build/dev/erlang/echo_int/_gleam_artefacts/echo_int@@main.erl deleted file mode 100644 index 15cc97b6857..00000000000 --- a/test-output/cases/echo_int/build/dev/erlang/echo_int/_gleam_artefacts/echo_int@@main.erl +++ /dev/null @@ -1,99 +0,0 @@ --module('echo_int@@main'). --export([run/1]). - --define(red, "\e[31;1m"). --define(grey, "\e[90m"). --define(reset_color, "\e[39m"). --define(reset_all, "\e[0m"). - -run(Module) -> - io:setopts(standard_io, [binary, {encoding, utf8}]), - io:setopts(standard_error, [{encoding, utf8}]), - process_flag(trap_exit, true), - Pid = spawn_link(fun() -> run_module(Module) end), - receive - {'EXIT', Pid, {Reason, StackTrace}} -> - print_error(exit, Reason, StackTrace), - init:stop(1) - end. - -run_module(Module) -> - try - {ok, _} = application:ensure_all_started('echo_int'), - erlang:process_flag(trap_exit, false), - Module:main(), - erlang:halt(0) - catch - Class:Reason:StackTrace -> - print_error(Class, Reason, StackTrace), - init:stop(1) - end. - -print_error(Class, Error, Stacktrace) -> - Printed = [ - ?red, "runtime error", ?reset_color, ": ", error_class(Class, Error), ?reset_all, - "\n\n", - error_message(Error), - "\n\n", - error_details(Class, Error), - "stacktrace:\n", - [error_frame(Line) || Line <- refine_first(Error, Stacktrace)] - ], - io:format(standard_error, "~ts~n", [Printed]). - -refine_first(#{gleam_error := _, line := L}, [{M, F, A, [{file, Fi} | _]} | S]) -> - [{M, F, A, [{file, Fi}, {line, L}]} | S]; -refine_first(_, S) -> - S. - -error_class(_, #{gleam_error := panic}) -> "panic"; -error_class(_, #{gleam_error := todo}) -> "todo"; -error_class(_, #{gleam_error := let_assert}) -> "let assert"; -error_class(Class, _) -> ["Erlang ", atom_to_binary(Class)]. - -error_message(#{gleam_error := _, message := M}) -> - M; -error_message(undef) -> - <<"A function was called but it did not exist."/utf8 >>; -error_message({case_clause, _}) -> - <<"No pattern matched in an Erlang case expression."/utf8>>; -error_message({badmatch, _}) -> - <<"An Erlang assignment pattern did not match."/utf8>>; -error_message(function_clause) -> - <<"No Erlang function clause matched the arguments it was called with."/utf8>>; -error_message(_) -> - <<"An error occurred outside of Gleam."/utf8>>. - -error_details(_, #{gleam_error := let_assert, value := V}) -> - ["unmatched value:\n ", print_term(V), $\n, $\n]; -error_details(_, {case_clause, V}) -> - ["unmatched value:\n ", print_term(V), $\n, $\n]; -error_details(_, {badmatch, V}) -> - ["unmatched value:\n ", print_term(V), $\n, $\n]; -error_details(_, #{gleam_error := _}) -> - []; -error_details(error, function_clause) -> - []; -error_details(error, undef) -> - []; -error_details(C, E) -> - ["erlang:", atom_to_binary(C), $(, print_term(E), $), $\n, $\n]. - -print_term(T) -> - try - gleam@string:inspect(T) - catch - _:_ -> io_lib:format("~p", [T]) - end. - -error_frame({?MODULE, _, _, _}) -> []; -error_frame({erl_eval, _, _, _}) -> []; -error_frame({init, _, _, _}) -> []; -error_frame({M, F, _, O}) -> - M1 = string:replace(atom_to_binary(M), "@", "/", all), - [" ", M1, $., atom_to_binary(F), error_frame_end(O), $\n]. - -error_frame_end([{file, Fi}, {line, L} | _]) -> - [?grey, $\s, Fi, $:, integer_to_binary(L), ?reset_all]; -error_frame_end(_) -> - [?grey, " unknown source", ?reset_all]. \ No newline at end of file diff --git a/test-output/cases/echo_int/build/dev/erlang/echo_int/_gleam_artefacts/gleam@@compile.erl b/test-output/cases/echo_int/build/dev/erlang/echo_int/_gleam_artefacts/gleam@@compile.erl deleted file mode 100644 index 3e0a645b737..00000000000 --- a/test-output/cases/echo_int/build/dev/erlang/echo_int/_gleam_artefacts/gleam@@compile.erl +++ /dev/null @@ -1,163 +0,0 @@ -#!/usr/bin/env escript --mode(compile). - -% TODO: Don't concurrently print warnings and errors -% TODO: Some tests - -main(_) -> compile_package_loop(). - -compile_package_loop() -> - case file:read_line(standard_io) of - eof -> ok; - {ok, Line} -> - Chars = unicode:characters_to_list(Line), - {ok, Tokens, _} = erl_scan:string(Chars), - {ok, {Lib, Out, Modules}} = erl_parse:parse_term(Tokens), - case compile_package(Lib, Out, Modules) of - ok -> io:put_chars("gleam-compile-result-ok\n"); - err -> io:put_chars("gleam-compile-result-error\n") - end, - compile_package_loop() - end. - -compile_package(Lib, Out, Modules) -> - IsElixirModule = fun(Module) -> - filename:extension(Module) =:= ".ex" - end, - {ElixirModules, ErlangModules} = lists:partition(IsElixirModule, Modules), - ok = configure_logging(), - ok = add_lib_to_erlang_path(Lib), - ok = filelib:ensure_dir([Out, $/]), - {ErlangOk, _ErlangBeams} = compile_erlang(ErlangModules, Out), - {ElixirOk, _ElixirBeams} = case ErlangOk of - true -> compile_elixir(ElixirModules, Out); - false -> {false, []} - end, - ok = del_lib_from_erlang_path(Lib), - case ErlangOk and ElixirOk of - true -> ok; - false -> err - end. - -compile_erlang(Modules, Out) -> - Workers = start_compiler_workers(Out), - ok = producer_loop(Modules, Workers), - collect_results({true, []}). - -collect_results(Acc = {Result, Beams}) -> - receive - {compiled, Beam} -> collect_results({Result, [Beam | Beams]}); - failed -> collect_results({false, Beams}) - after 0 -> Acc - end. - -producer_loop([], 0) -> - ok; -producer_loop([], Workers) -> - receive - {work_please, _} -> producer_loop([], Workers - 1) - end; -producer_loop([Module | Modules], Workers) -> - receive - {work_please, Worker} -> - erlang:send(Worker, {module, Module}), - producer_loop(Modules, Workers) - end. - -start_compiler_workers(Out) -> - Parent = self(), - NumSchedulers = erlang:system_info(schedulers), - SpawnWorker = fun(_) -> - erlang:spawn_link(fun() -> worker_loop(Parent, Out) end) - end, - lists:foreach(SpawnWorker, lists:seq(1, NumSchedulers)), - NumSchedulers. - -worker_loop(Parent, Out) -> - Options = [report_errors, report_warnings, debug_info, {outdir, Out}], - erlang:send(Parent, {work_please, self()}), - receive - {module, Module} -> - log({compiling, Module}), - case compile:file(Module, Options) of - {ok, ModuleName} -> - Beam = filename:join(Out, ModuleName) ++ ".beam", - Message = {compiled, Beam}, - log(Message), - erlang:send(Parent, Message); - error -> - log({failed, Module}), - erlang:send(Parent, failed) - end, - worker_loop(Parent, Out) - end. - -compile_elixir(Modules, Out) -> - Error = [ - "The program elixir was not found. Is it installed?", - $\n, - "Documentation for installing Elixir can be viewed here:", - $\n, - "https://elixir-lang.org/install.html" - ], - case Modules of - [] -> {true, []}; - _ -> - log({starting, "compiler.app"}), - ok = application:start(compiler), - log({starting, "elixir.app"}), - case application:start(elixir) of - ok -> do_compile_elixir(Modules, Out); - _ -> - io:put_chars(standard_error, [Error, $\n]), - {false, []} - end - end. - -do_compile_elixir(Modules, Out) -> - ModuleBins = lists:map(fun(Module) -> - log({compiling, Module}), - list_to_binary(Module) - end, Modules), - OutBin = list_to_binary(Out), - Options = [{dest, OutBin}], - % Silence "redefining module" warnings. - % Compiled modules in the build directory are added to the code path. - % These warnings result from recompiling loaded modules. - % TODO: This line can likely be removed if/when the build directory is cleaned before every compilation. - 'Elixir.Code':compiler_options([{ignore_module_conflict, true}]), - case 'Elixir.Kernel.ParallelCompiler':compile_to_path(ModuleBins, OutBin, Options) of - {ok, ModuleAtoms, _} -> - ToBeam = fun(ModuleAtom) -> - Beam = filename:join(Out, atom_to_list(ModuleAtom)) ++ ".beam", - log({compiled, Beam}), - Beam - end, - {true, lists:map(ToBeam, ModuleAtoms)}; - {error, Errors, _} -> - % Log all filenames associated with modules that failed to compile. - % Note: The compiler prints compilation errors upon encountering them. - ErrorFiles = lists:usort([File || {File, _, _} <- Errors]), - Log = fun(File) -> - log({failed, binary_to_list(File)}) - end, - lists:foreach(Log, ErrorFiles), - {false, []}; - _ -> {false, []} - end. - -add_lib_to_erlang_path(Lib) -> - code:add_paths(filelib:wildcard([Lib, "/*/ebin"])). - -del_lib_from_erlang_path(Lib) -> - code:del_paths(filelib:wildcard([Lib, "/*/ebin"])). - -configure_logging() -> - Enabled = os:getenv("GLEAM_LOG") /= false, - persistent_term:put(gleam_logging_enabled, Enabled). - -log(Term) -> - case persistent_term:get(gleam_logging_enabled) of - true -> erlang:display(Term), ok; - false -> ok - end. diff --git a/test-output/cases/echo_int/build/dev/erlang/echo_int/_gleam_artefacts/main.cache b/test-output/cases/echo_int/build/dev/erlang/echo_int/_gleam_artefacts/main.cache deleted file mode 100644 index a52c32a59ee..00000000000 Binary files a/test-output/cases/echo_int/build/dev/erlang/echo_int/_gleam_artefacts/main.cache and /dev/null differ diff --git a/test-output/cases/echo_int/build/dev/erlang/echo_int/_gleam_artefacts/main.cache_meta b/test-output/cases/echo_int/build/dev/erlang/echo_int/_gleam_artefacts/main.cache_meta deleted file mode 100644 index 70183272335..00000000000 Binary files a/test-output/cases/echo_int/build/dev/erlang/echo_int/_gleam_artefacts/main.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_int/build/dev/erlang/echo_int/_gleam_artefacts/main.cache_warnings b/test-output/cases/echo_int/build/dev/erlang/echo_int/_gleam_artefacts/main.cache_warnings deleted file mode 100644 index 1b1cb4d44c5..00000000000 Binary files a/test-output/cases/echo_int/build/dev/erlang/echo_int/_gleam_artefacts/main.cache_warnings and /dev/null differ diff --git a/test-output/cases/echo_int/build/dev/erlang/echo_int/_gleam_artefacts/main.erl b/test-output/cases/echo_int/build/dev/erlang/echo_int/_gleam_artefacts/main.erl deleted file mode 100644 index 0546d468132..00000000000 --- a/test-output/cases/echo_int/build/dev/erlang/echo_int/_gleam_artefacts/main.erl +++ /dev/null @@ -1,191 +0,0 @@ --module(main). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([main/0]). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_int/src/main.gleam", 1). --spec main() -> integer(). -main() -> - echo(1, "src/main.gleam", 2), - echo(2, "src/main.gleam", 3), - echo(100000, "src/main.gleam", 4). - --define(is_lowercase_char(X), (X > 96 andalso X < 123)). --define(is_underscore_char(X), (X == 95)). --define(is_digit_char(X), (X > 47 andalso X < 58)). --define(could_be_record(Tuple), - erlang:is_tuple(Tuple) andalso - erlang:is_atom(erlang:element(1, Tuple)) andalso - erlang:element(1, Tuple) =/= false andalso - erlang:element(1, Tuple) =/= true andalso - erlang:element(1, Tuple) =/= nil -). --define(is_atom_char(C), - (?is_lowercase_char(C) orelse - ?is_underscore_char(C) orelse - ?is_digit_char(C)) -). - --define(grey, "\e[90m"). --define(reset_color, "\e[39m"). - -echo(Value, File, Line) -> - StringLine = erlang:integer_to_list(Line), - StringValue = echo@inspect(Value), - io:put_chars( - standard_error, - [?grey, File, $:, StringLine, ?reset_color, $\n, StringValue, $\n] - ), - Value. - -echo@inspect(Value) -> - case Value of - nil -> "Nil"; - true -> "True"; - false -> "False"; - Int when erlang:is_integer(Int) -> erlang:integer_to_list(Int); - Float when erlang:is_float(Float) -> io_lib_format:fwrite_g(Float); - Binary when erlang:is_binary(Binary) -> inspect@binary(Binary); - Bits when erlang:is_bitstring(Bits) -> inspect@bit_array(Bits); - Atom when erlang:is_atom(Atom) -> inspect@atom(Atom); - List when erlang:is_list(List) -> inspect@list(List); - Map when erlang:is_map(Map) -> inspect@map(Map); - Record when ?could_be_record(Record) -> inspect@record(Record); - Tuple when erlang:is_tuple(Tuple) -> inspect@tuple(Tuple); - Function when erlang:is_function(Function) -> inspect@function(Function); - Any -> ["//erl(", io_lib:format("~p", [Any]), ")"] - end. - -inspect@bit_array(Bits) -> - Pieces = inspect@bit_array_pieces(Bits, []), - Inner = lists:join(", ", lists:reverse(Pieces)), - ["<<", Inner, ">>"]. - -inspect@bit_array_pieces(Bits, Acc) -> - case Bits of - <<>> -> - Acc; - <> -> - inspect@bit_array_pieces(Rest, [erlang:integer_to_binary(Byte) | Acc]); - _ -> - Size = erlang:bit_size(Bits), - <> = Bits, - SizeString = [":size(", erlang:integer_to_binary(Size), ")"], - Piece = [erlang:integer_to_binary(RemainingBits), SizeString], - [Piece | Acc] - end. - -inspect@binary(Binary) -> - case inspect@maybe_utf8_string(Binary, <<>>) of - {ok, InspectedUtf8String} -> - InspectedUtf8String; - {error, not_a_utf8_string} -> - Segments = [erlang:integer_to_list(X) || <> <= Binary], - ["<<", lists:join(", ", Segments), ">>"] - end. - -inspect@atom(Atom) -> - Binary = erlang:atom_to_binary(Atom), - case inspect@maybe_gleam_atom(Binary, none, <<>>) of - {ok, Inspected} -> Inspected; - {error, _} -> ["atom.create_from_string(\"", Binary, "\")"] - end. - -inspect@list(List) -> - case inspect@proper_or_improper_list(List) of - {proper, Elements} -> ["[", Elements, "]"]; - {improper, Elements} -> ["//erl([", Elements, "])"] - end. - -inspect@map(Map) -> - Fields = [ - [<<"#(">>, echo@inspect(Key), <<", ">>, echo@inspect(Value), <<")">>] - || {Key, Value} <- maps:to_list(Map) - ], - ["dict.from_list([", lists:join(", ", Fields), "])"]. - -inspect@record(Record) -> - [Atom | ArgsList] = erlang:tuple_to_list(Record), - Args = lists:join(", ", lists:map(fun echo@inspect/1, ArgsList)), - [echo@inspect(Atom), "(", Args, ")"]. - -inspect@tuple(Tuple) -> - Elements = lists:map(fun echo@inspect/1, erlang:tuple_to_list(Tuple)), - ["#(", lists:join(", ", Elements), ")"]. - -inspect@function(Function) -> - {arity, Arity} = erlang:fun_info(Function, arity), - ArgsAsciiCodes = lists:seq($a, $a + Arity - 1), - Args = lists:join(", ", lists:map(fun(Arg) -> <> end, ArgsAsciiCodes)), - ["//fn(", Args, ") { ... }"]. - -inspect@maybe_utf8_string(Binary, Acc) -> - case Binary of - <<>> -> - {ok, <<$", Acc/binary, $">>}; - <> -> - Escaped = inspect@escape_grapheme(First), - inspect@maybe_utf8_string(Rest, <>); - _ -> - {error, not_a_utf8_string} - end. - -inspect@escape_grapheme(Char) -> - case Char of - $" -> <<$\\, $">>; - $\\ -> <<$\\, $\\>>; - $\r -> <<$\\, $r>>; - $\n -> <<$\\, $n>>; - $\t -> <<$\\, $t>>; - $\f -> <<$\\, $f>>; - X when X > 126, X < 160 -> inspect@convert_to_u(X); - X when X < 32 -> inspect@convert_to_u(X); - Other -> <> - end. - -inspect@convert_to_u(Code) -> - erlang:list_to_binary(io_lib:format("\\u{~4.16.0B}", [Code])). - -inspect@proper_or_improper_list(List) -> - case List of - [] -> - {proper, []}; - [First] -> - {proper, [echo@inspect(First)]}; - [First | Rest] when erlang:is_list(Rest) -> - {Kind, Inspected} = inspect@proper_or_improper_list(Rest), - {Kind, [echo@inspect(First), ", " | Inspected]}; - [First | ImproperRest] -> - {improper, [echo@inspect(First), " | ", echo@inspect(ImproperRest)]} - end. - -inspect@maybe_gleam_atom(Atom, PrevChar, Acc) -> - case {Atom, PrevChar} of - {<<>>, none} -> - {error, nil}; - {<>, none} when ?is_digit_char(First) -> - {error, nil}; - {<<"_", _/binary>>, none} -> - {error, nil}; - {<<"_">>, _} -> - {error, nil}; - {<<"_", _/binary>>, $_} -> - {error, nil}; - {<>, _} when not ?is_atom_char(First) -> - {error, nil}; - {<>, none} -> - inspect@maybe_gleam_atom(Rest, First, <>); - {<<"_", Rest/binary>>, _} -> - inspect@maybe_gleam_atom(Rest, $_, Acc); - {<>, $_} -> - inspect@maybe_gleam_atom(Rest, First, <>); - {<>, _} -> - inspect@maybe_gleam_atom(Rest, First, <>); - {<<>>, _} -> - {ok, Acc}; - _ -> - erlang:throw({gleam_error, echo, Atom, PrevChar, Acc}) - end. - -inspect@uppercase(X) -> X - 32. - diff --git a/test-output/cases/echo_int/build/dev/erlang/echo_int/ebin/echo_int.app b/test-output/cases/echo_int/build/dev/erlang/echo_int/ebin/echo_int.app deleted file mode 100644 index c2bc7564e1e..00000000000 --- a/test-output/cases/echo_int/build/dev/erlang/echo_int/ebin/echo_int.app +++ /dev/null @@ -1,7 +0,0 @@ -{application, echo_int, [ - {vsn, "1.0.0"}, - {applications, []}, - {description, ""}, - {modules, [main]}, - {registered, []} -]}. diff --git a/test-output/cases/echo_int/build/dev/erlang/gleam_version b/test-output/cases/echo_int/build/dev/erlang/gleam_version deleted file mode 100644 index 3e1ad720b13..00000000000 --- a/test-output/cases/echo_int/build/dev/erlang/gleam_version +++ /dev/null @@ -1 +0,0 @@ -1.5.0 \ No newline at end of file diff --git a/test-output/cases/echo_int/build/dev/javascript/echo_int/_gleam_artefacts/main.cache b/test-output/cases/echo_int/build/dev/javascript/echo_int/_gleam_artefacts/main.cache deleted file mode 100644 index 77c8e292ad3..00000000000 Binary files a/test-output/cases/echo_int/build/dev/javascript/echo_int/_gleam_artefacts/main.cache and /dev/null differ diff --git a/test-output/cases/echo_int/build/dev/javascript/echo_int/_gleam_artefacts/main.cache_meta b/test-output/cases/echo_int/build/dev/javascript/echo_int/_gleam_artefacts/main.cache_meta deleted file mode 100644 index 70183272335..00000000000 Binary files a/test-output/cases/echo_int/build/dev/javascript/echo_int/_gleam_artefacts/main.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_int/build/dev/javascript/echo_int/_gleam_artefacts/main.cache_warnings b/test-output/cases/echo_int/build/dev/javascript/echo_int/_gleam_artefacts/main.cache_warnings deleted file mode 100644 index 1b1cb4d44c5..00000000000 Binary files a/test-output/cases/echo_int/build/dev/javascript/echo_int/_gleam_artefacts/main.cache_warnings and /dev/null differ diff --git a/test-output/cases/echo_int/build/dev/javascript/echo_int/gleam.main.mjs b/test-output/cases/echo_int/build/dev/javascript/echo_int/gleam.main.mjs deleted file mode 100644 index e230911e646..00000000000 --- a/test-output/cases/echo_int/build/dev/javascript/echo_int/gleam.main.mjs +++ /dev/null @@ -1,2 +0,0 @@ -import { main } from "./main.mjs"; -main(); diff --git a/test-output/cases/echo_int/build/dev/javascript/echo_int/gleam.mjs b/test-output/cases/echo_int/build/dev/javascript/echo_int/gleam.mjs deleted file mode 100644 index 197cbbc35d4..00000000000 --- a/test-output/cases/echo_int/build/dev/javascript/echo_int/gleam.mjs +++ /dev/null @@ -1 +0,0 @@ -export * from "../prelude.mjs"; diff --git a/test-output/cases/echo_int/build/dev/javascript/echo_int/main.mjs b/test-output/cases/echo_int/build/dev/javascript/echo_int/main.mjs deleted file mode 100644 index e5223a3df0c..00000000000 --- a/test-output/cases/echo_int/build/dev/javascript/echo_int/main.mjs +++ /dev/null @@ -1,129 +0,0 @@ -import { - BitArray as $BitArray, - List as $List, - UtfCodepoint as $UtfCodepoint, - CustomType as $CustomType, -} from "./gleam.mjs"; - -export function main() { - echo(1, "src/main.gleam", 2); - echo(2, "src/main.gleam", 3); - return echo(100_000, "src/main.gleam", 4); -} - -function echo(value, file, line) { - const grey = "\u001b[90m"; - const reset_color = "\u001b[39m"; - const file_line = `${file}:${line}`; - const string_value = echo$inspect(value); - - if (typeof process === "object" && process.stderr?.write) { - // If we're in Node.js, use `stderr` - const string = `${grey}${file_line}${reset_color}\n${string_value}\n`; - process.stderr.write(string); - } else if (typeof Deno === "object") { - // If we're in Deno, use `stderr` - const string = `${grey}${file_line}${reset_color}\n${string_value}\n`; - Deno.stderr.writeSync(new TextEncoder().encode(string)); - } else { - // Otherwise, use `console.log` - // The browser's console.log doesn't support ansi escape codes - const string = `${file_line}\n${string_value}`; - console.log(string); - } - - return value; -} - -function echo$inspectString(str) { - let new_str = '"'; - for (let i = 0; i < str.length; i++) { - let char = str[i]; - if (char == "\n") new_str += "\\n"; - else if (char == "\r") new_str += "\\r"; - else if (char == "\t") new_str += "\\t"; - else if (char == "\f") new_str += "\\f"; - else if (char == "\\") new_str += "\\\\"; - else if (char == '"') new_str += '\\"'; - else if (char < " " || (char > "~" && char < "\u{00A0}")) { - new_str += "\\u{" + char.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0") + "}"; - } else { - new_str += char; - } - } - new_str += '"'; - return new_str; -} - -function echo$inspectDict(map) { - let body = "dict.from_list(["; - let first = true; - map.forEach((value, key) => { - if (!first) body = body + ", "; - body = body + "#(" + echo$inspect(key) + ", " + echo$inspect(value) + ")"; - first = false; - }); - return body + "])"; -} - -function echo$inspectCustomType(record) { - const props = Object.keys(record) - .map((label) => { - const value = echo$inspect(record[label]); - return isNaN(parseInt(label)) ? `${label}: ${value}` : value; - }) - .join(", "); - return props ? `${record.constructor.name}(${props})` : record.constructor.name; -} - -function echo$inspectObject(v) { - const name = Object.getPrototypeOf(v)?.constructor?.name || "Object"; - const props = []; - for (const k of Object.keys(v)) { - props.push(`${echo$inspect(k)}: ${echo$inspect(v[k])}`); - } - const body = props.length ? " " + props.join(", ") + " " : ""; - const head = name === "Object" ? "" : name + " "; - return `//js(${head}{${body}})`; -} - -function echo$inspect(v) { - const t = typeof v; - if (v === true) return "True"; - if (v === false) return "False"; - if (v === null) return "//js(null)"; - if (v === undefined) return "Nil"; - if (t === "string") return echo$inspectString(v); - if (t === "bigint" || t === "number") return v.toString(); - if (Array.isArray(v)) return `#(${v.map(echo$inspect).join(", ")})`; - if (v instanceof $List) return `[${v.toArray().map(echo$inspect).join(", ")}]`; - if (v instanceof $UtfCodepoint) return `//utfcodepoint(${String.fromCodePoint(v.value)})`; - if (v instanceof $BitArray) return `<<${Array.from(v.buffer).join(", ")}>>`; - if (v instanceof $CustomType) return echo$inspectCustomType(v); - if (echo$isDict(v)) return echo$inspectDict(v); - if (v instanceof Set) return `//js(Set(${[...v].map(echo$inspect).join(", ")}))`; - if (v instanceof RegExp) return `//js(${v})`; - if (v instanceof Date) return `//js(Date("${v.toISOString()}"))`; - if (v instanceof Function) { - const args = []; - for (const i of Array(v.length).keys()) args.push(String.fromCharCode(i + 97)); - return `//fn(${args.join(", ")}) { ... }`; - } - return echo$inspectObject(v); -} - -function echo$isDict(value) { - try { - // We can only check if an object is a stdlib Dict if it is one of the - // project's dependencies. - // The `Dict` class is the default export of `stdlib/dict.mjs` - // that we import as `$stdlib$dict`. - return value instanceof $stdlib$dict.default; - } catch { - // If stdlib is not one of the project's dependencies then `$stdlib$dict` - // will not have been imported and the check will throw an exception meaning - // we can't check if something is actually a `Dict`. - return false; - } -} - diff --git a/test-output/cases/echo_int/build/dev/javascript/gleam_version b/test-output/cases/echo_int/build/dev/javascript/gleam_version deleted file mode 100644 index 3e1ad720b13..00000000000 --- a/test-output/cases/echo_int/build/dev/javascript/gleam_version +++ /dev/null @@ -1 +0,0 @@ -1.5.0 \ No newline at end of file diff --git a/test-output/cases/echo_int/build/dev/javascript/prelude.mjs b/test-output/cases/echo_int/build/dev/javascript/prelude.mjs deleted file mode 100644 index d2adeef273f..00000000000 --- a/test-output/cases/echo_int/build/dev/javascript/prelude.mjs +++ /dev/null @@ -1,455 +0,0 @@ -// Values marked with @internal are not part of the public API and may change -// without notice. - -export class CustomType { - withFields(fields) { - let properties = Object.keys(this).map((label) => - label in fields ? fields[label] : this[label], - ); - return new this.constructor(...properties); - } -} - -export class List { - static fromArray(array, tail) { - let t = tail || new Empty(); - for (let i = array.length - 1; i >= 0; --i) { - t = new NonEmpty(array[i], t); - } - return t; - } - - [Symbol.iterator]() { - return new ListIterator(this); - } - - toArray() { - return [...this]; - } - - // @internal - atLeastLength(desired) { - for (let _ of this) { - if (desired <= 0) return true; - desired--; - } - return desired <= 0; - } - - // @internal - hasLength(desired) { - for (let _ of this) { - if (desired <= 0) return false; - desired--; - } - return desired === 0; - } - - // @internal - countLength() { - let length = 0; - for (let _ of this) length++; - return length; - } -} - -// @internal -export function prepend(element, tail) { - return new NonEmpty(element, tail); -} - -export function toList(elements, tail) { - return List.fromArray(elements, tail); -} - -// @internal -class ListIterator { - #current; - - constructor(current) { - this.#current = current; - } - - next() { - if (this.#current instanceof Empty) { - return { done: true }; - } else { - let { head, tail } = this.#current; - this.#current = tail; - return { value: head, done: false }; - } - } -} - -export class Empty extends List {} - -export class NonEmpty extends List { - constructor(head, tail) { - super(); - this.head = head; - this.tail = tail; - } -} - -export class BitArray { - constructor(buffer) { - if (!(buffer instanceof Uint8Array)) { - throw "BitArray can only be constructed from a Uint8Array"; - } - this.buffer = buffer; - } - - // @internal - get length() { - return this.buffer.length; - } - - // @internal - byteAt(index) { - return this.buffer[index]; - } - - // @internal - floatFromSlice(start, end, isBigEndian) { - return byteArrayToFloat(this.buffer, start, end, isBigEndian); - } - - // @internal - intFromSlice(start, end, isBigEndian, isSigned) { - return byteArrayToInt(this.buffer, start, end, isBigEndian, isSigned); - } - - // @internal - binaryFromSlice(start, end) { - return new BitArray(this.buffer.slice(start, end)); - } - - // @internal - sliceAfter(index) { - return new BitArray(this.buffer.slice(index)); - } -} - -export class UtfCodepoint { - constructor(value) { - this.value = value; - } -} - -// @internal -export function toBitArray(segments) { - if (segments.length === 0) { - return new BitArray(new Uint8Array()); - } - - if (segments.length === 1) { - // When there is a single Uint8Array segment, pass it directly to the bit - // array constructor to avoid a copy - if (segments[0] instanceof Uint8Array) { - return new BitArray(segments[0]); - } - - return new BitArray(new Uint8Array(segments)); - } - - // Count the total number of bytes, and check if there are any Uint8Array - // segments - let bytes = 0; - let hasUint8ArraySegment = false; - for (const segment of segments) { - if (segment instanceof Uint8Array) { - bytes += segment.byteLength; - hasUint8ArraySegment = true; - } else { - bytes++; - } - } - - // If there aren't any Uint8Array segments then pass the segments array - // directly to the Uint8Array constructor - if (!hasUint8ArraySegment) { - return new BitArray(new Uint8Array(segments)); - } - - // Copy the segments into a Uint8Array - let u8Array = new Uint8Array(bytes); - let cursor = 0; - for (let segment of segments) { - if (segment instanceof Uint8Array) { - u8Array.set(segment, cursor); - cursor += segment.byteLength; - } else { - u8Array[cursor] = segment; - cursor++; - } - } - - return new BitArray(u8Array); -} - -// @internal -// Derived from this answer https://stackoverflow.com/questions/8482309/converting-javascript-integer-to-byte-array-and-back -export function sizedInt(value, size, isBigEndian) { - if (size < 0) { - return new Uint8Array(); - } - if (size % 8 != 0) { - const msg = `Bit arrays must be byte aligned on JavaScript, got size of ${size} bits`; - throw new globalThis.Error(msg); - } - - const byteArray = new Uint8Array(size / 8); - - // Convert negative number to two's complement representation - if (value < 0) { - value = 2 ** size + value; - } - - if (isBigEndian) { - for (let i = byteArray.length - 1; i >= 0; i--) { - const byte = value % 256; - byteArray[i] = byte; - value = (value - byte) / 256; - } - } else { - for (let i = 0; i < byteArray.length; i++) { - const byte = value % 256; - byteArray[i] = byte; - value = (value - byte) / 256; - } - } - - return byteArray; -} - -// @internal -export function byteArrayToInt(byteArray, start, end, isBigEndian, isSigned) { - let value = 0; - - // Read bytes as an unsigned integer value - if (isBigEndian) { - for (let i = start; i < end; i++) { - value = value * 256 + byteArray[i]; - } - } else { - for (let i = end - 1; i >= start; i--) { - value = value * 256 + byteArray[i]; - } - } - - if (isSigned) { - const byteSize = end - start; - - const highBit = 2 ** (byteSize * 8 - 1); - - // If the high bit is set and this is a signed integer, reinterpret as - // two's complement - if (value >= highBit) { - value -= highBit * 2; - } - } - - return value; -} - -// @internal -export function byteArrayToFloat(byteArray, start, end, isBigEndian) { - const view = new DataView(byteArray.buffer); - - const byteSize = end - start; - - if (byteSize === 8) { - return view.getFloat64(start, !isBigEndian); - } else if (byteSize === 4) { - return view.getFloat32(start, !isBigEndian); - } else { - const msg = `Sized floats must be 32-bit or 64-bit on JavaScript, got size of ${byteSize * 8} bits`; - throw new globalThis.Error(msg); - } -} - -// @internal -export function stringBits(string) { - return new TextEncoder().encode(string); -} - -// @internal -export function codepointBits(codepoint) { - return stringBits(String.fromCodePoint(codepoint.value)); -} - -// @internal -export function sizedFloat(float, size, isBigEndian) { - if (size !== 32 && size !== 64) { - const msg = `Sized floats must be 32-bit or 64-bit on JavaScript, got size of ${size} bits`; - throw new globalThis.Error(msg); - } - - const byteArray = new Uint8Array(size / 8); - - const view = new DataView(byteArray.buffer); - - if (size == 64) { - view.setFloat64(0, float, !isBigEndian); - } else if (size === 32) { - view.setFloat32(0, float, !isBigEndian); - } - - return byteArray; -} - -export class Result extends CustomType { - // @internal - static isResult(data) { - return data instanceof Result; - } -} - -export class Ok extends Result { - constructor(value) { - super(); - this[0] = value; - } - - // @internal - isOk() { - return true; - } -} - -export class Error extends Result { - constructor(detail) { - super(); - this[0] = detail; - } - - // @internal - isOk() { - return false; - } -} - -export function isEqual(x, y) { - let values = [x, y]; - - while (values.length) { - let a = values.pop(); - let b = values.pop(); - if (a === b) continue; - - if (!isObject(a) || !isObject(b)) return false; - let unequal = - !structurallyCompatibleObjects(a, b) || - unequalDates(a, b) || - unequalBuffers(a, b) || - unequalArrays(a, b) || - unequalMaps(a, b) || - unequalSets(a, b) || - unequalRegExps(a, b); - if (unequal) return false; - - const proto = Object.getPrototypeOf(a); - if (proto !== null && typeof proto.equals === "function") { - try { - if (a.equals(b)) continue; - else return false; - } catch {} - } - - let [keys, get] = getters(a); - for (let k of keys(a)) { - values.push(get(a, k), get(b, k)); - } - } - - return true; -} - -function getters(object) { - if (object instanceof Map) { - return [(x) => x.keys(), (x, y) => x.get(y)]; - } else { - let extra = object instanceof globalThis.Error ? ["message"] : []; - return [(x) => [...extra, ...Object.keys(x)], (x, y) => x[y]]; - } -} - -function unequalDates(a, b) { - return a instanceof Date && (a > b || a < b); -} - -function unequalBuffers(a, b) { - return ( - a.buffer instanceof ArrayBuffer && - a.BYTES_PER_ELEMENT && - !(a.byteLength === b.byteLength && a.every((n, i) => n === b[i])) - ); -} - -function unequalArrays(a, b) { - return Array.isArray(a) && a.length !== b.length; -} - -function unequalMaps(a, b) { - return a instanceof Map && a.size !== b.size; -} - -function unequalSets(a, b) { - return ( - a instanceof Set && (a.size != b.size || [...a].some((e) => !b.has(e))) - ); -} - -function unequalRegExps(a, b) { - return a instanceof RegExp && (a.source !== b.source || a.flags !== b.flags); -} - -function isObject(a) { - return typeof a === "object" && a !== null; -} - -function structurallyCompatibleObjects(a, b) { - if (typeof a !== "object" && typeof b !== "object" && (!a || !b)) - return false; - - let nonstructural = [Promise, WeakSet, WeakMap, Function]; - if (nonstructural.some((c) => a instanceof c)) return false; - - return a.constructor === b.constructor; -} - -// @internal -export function remainderInt(a, b) { - if (b === 0) { - return 0; - } else { - return a % b; - } -} - -// @internal -export function divideInt(a, b) { - return Math.trunc(divideFloat(a, b)); -} - -// @internal -export function divideFloat(a, b) { - if (b === 0) { - return 0; - } else { - return a / b; - } -} - -// @internal -export function makeError(variant, module, line, fn, message, extra) { - let error = new globalThis.Error(message); - error.gleam_error = variant; - error.module = module; - error.line = line; - error.function = fn; - // TODO: Remove this with Gleam v2.0.0 - error.fn = fn; - for (let k in extra) error[k] = extra[k]; - return error; -} diff --git a/test-output/cases/echo_int/build/packages/packages.toml b/test-output/cases/echo_int/build/packages/packages.toml deleted file mode 100644 index e74c18552bb..00000000000 --- a/test-output/cases/echo_int/build/packages/packages.toml +++ /dev/null @@ -1 +0,0 @@ -[packages] diff --git a/test-output/cases/echo_int/manifest.toml b/test-output/cases/echo_int/manifest.toml deleted file mode 100644 index c5d779a3f81..00000000000 --- a/test-output/cases/echo_int/manifest.toml +++ /dev/null @@ -1,7 +0,0 @@ -# This file was generated by Gleam -# You typically do not need to edit this file - -packages = [ -] - -[requirements] diff --git a/test-output/cases/echo_list/build/dev/erlang/echo_list/_gleam_artefacts/echo_list@@main.erl b/test-output/cases/echo_list/build/dev/erlang/echo_list/_gleam_artefacts/echo_list@@main.erl deleted file mode 100644 index 7be1b9ec44f..00000000000 --- a/test-output/cases/echo_list/build/dev/erlang/echo_list/_gleam_artefacts/echo_list@@main.erl +++ /dev/null @@ -1,99 +0,0 @@ --module('echo_list@@main'). --export([run/1]). - --define(red, "\e[31;1m"). --define(grey, "\e[90m"). --define(reset_color, "\e[39m"). --define(reset_all, "\e[0m"). - -run(Module) -> - io:setopts(standard_io, [binary, {encoding, utf8}]), - io:setopts(standard_error, [{encoding, utf8}]), - process_flag(trap_exit, true), - Pid = spawn_link(fun() -> run_module(Module) end), - receive - {'EXIT', Pid, {Reason, StackTrace}} -> - print_error(exit, Reason, StackTrace), - init:stop(1) - end. - -run_module(Module) -> - try - {ok, _} = application:ensure_all_started('echo_list'), - erlang:process_flag(trap_exit, false), - Module:main(), - erlang:halt(0) - catch - Class:Reason:StackTrace -> - print_error(Class, Reason, StackTrace), - init:stop(1) - end. - -print_error(Class, Error, Stacktrace) -> - Printed = [ - ?red, "runtime error", ?reset_color, ": ", error_class(Class, Error), ?reset_all, - "\n\n", - error_message(Error), - "\n\n", - error_details(Class, Error), - "stacktrace:\n", - [error_frame(Line) || Line <- refine_first(Error, Stacktrace)] - ], - io:format(standard_error, "~ts~n", [Printed]). - -refine_first(#{gleam_error := _, line := L}, [{M, F, A, [{file, Fi} | _]} | S]) -> - [{M, F, A, [{file, Fi}, {line, L}]} | S]; -refine_first(_, S) -> - S. - -error_class(_, #{gleam_error := panic}) -> "panic"; -error_class(_, #{gleam_error := todo}) -> "todo"; -error_class(_, #{gleam_error := let_assert}) -> "let assert"; -error_class(Class, _) -> ["Erlang ", atom_to_binary(Class)]. - -error_message(#{gleam_error := _, message := M}) -> - M; -error_message(undef) -> - <<"A function was called but it did not exist."/utf8 >>; -error_message({case_clause, _}) -> - <<"No pattern matched in an Erlang case expression."/utf8>>; -error_message({badmatch, _}) -> - <<"An Erlang assignment pattern did not match."/utf8>>; -error_message(function_clause) -> - <<"No Erlang function clause matched the arguments it was called with."/utf8>>; -error_message(_) -> - <<"An error occurred outside of Gleam."/utf8>>. - -error_details(_, #{gleam_error := let_assert, value := V}) -> - ["unmatched value:\n ", print_term(V), $\n, $\n]; -error_details(_, {case_clause, V}) -> - ["unmatched value:\n ", print_term(V), $\n, $\n]; -error_details(_, {badmatch, V}) -> - ["unmatched value:\n ", print_term(V), $\n, $\n]; -error_details(_, #{gleam_error := _}) -> - []; -error_details(error, function_clause) -> - []; -error_details(error, undef) -> - []; -error_details(C, E) -> - ["erlang:", atom_to_binary(C), $(, print_term(E), $), $\n, $\n]. - -print_term(T) -> - try - gleam@string:inspect(T) - catch - _:_ -> io_lib:format("~p", [T]) - end. - -error_frame({?MODULE, _, _, _}) -> []; -error_frame({erl_eval, _, _, _}) -> []; -error_frame({init, _, _, _}) -> []; -error_frame({M, F, _, O}) -> - M1 = string:replace(atom_to_binary(M), "@", "/", all), - [" ", M1, $., atom_to_binary(F), error_frame_end(O), $\n]. - -error_frame_end([{file, Fi}, {line, L} | _]) -> - [?grey, $\s, Fi, $:, integer_to_binary(L), ?reset_all]; -error_frame_end(_) -> - [?grey, " unknown source", ?reset_all]. \ No newline at end of file diff --git a/test-output/cases/echo_list/build/dev/erlang/echo_list/_gleam_artefacts/gleam@@compile.erl b/test-output/cases/echo_list/build/dev/erlang/echo_list/_gleam_artefacts/gleam@@compile.erl deleted file mode 100644 index 3e0a645b737..00000000000 --- a/test-output/cases/echo_list/build/dev/erlang/echo_list/_gleam_artefacts/gleam@@compile.erl +++ /dev/null @@ -1,163 +0,0 @@ -#!/usr/bin/env escript --mode(compile). - -% TODO: Don't concurrently print warnings and errors -% TODO: Some tests - -main(_) -> compile_package_loop(). - -compile_package_loop() -> - case file:read_line(standard_io) of - eof -> ok; - {ok, Line} -> - Chars = unicode:characters_to_list(Line), - {ok, Tokens, _} = erl_scan:string(Chars), - {ok, {Lib, Out, Modules}} = erl_parse:parse_term(Tokens), - case compile_package(Lib, Out, Modules) of - ok -> io:put_chars("gleam-compile-result-ok\n"); - err -> io:put_chars("gleam-compile-result-error\n") - end, - compile_package_loop() - end. - -compile_package(Lib, Out, Modules) -> - IsElixirModule = fun(Module) -> - filename:extension(Module) =:= ".ex" - end, - {ElixirModules, ErlangModules} = lists:partition(IsElixirModule, Modules), - ok = configure_logging(), - ok = add_lib_to_erlang_path(Lib), - ok = filelib:ensure_dir([Out, $/]), - {ErlangOk, _ErlangBeams} = compile_erlang(ErlangModules, Out), - {ElixirOk, _ElixirBeams} = case ErlangOk of - true -> compile_elixir(ElixirModules, Out); - false -> {false, []} - end, - ok = del_lib_from_erlang_path(Lib), - case ErlangOk and ElixirOk of - true -> ok; - false -> err - end. - -compile_erlang(Modules, Out) -> - Workers = start_compiler_workers(Out), - ok = producer_loop(Modules, Workers), - collect_results({true, []}). - -collect_results(Acc = {Result, Beams}) -> - receive - {compiled, Beam} -> collect_results({Result, [Beam | Beams]}); - failed -> collect_results({false, Beams}) - after 0 -> Acc - end. - -producer_loop([], 0) -> - ok; -producer_loop([], Workers) -> - receive - {work_please, _} -> producer_loop([], Workers - 1) - end; -producer_loop([Module | Modules], Workers) -> - receive - {work_please, Worker} -> - erlang:send(Worker, {module, Module}), - producer_loop(Modules, Workers) - end. - -start_compiler_workers(Out) -> - Parent = self(), - NumSchedulers = erlang:system_info(schedulers), - SpawnWorker = fun(_) -> - erlang:spawn_link(fun() -> worker_loop(Parent, Out) end) - end, - lists:foreach(SpawnWorker, lists:seq(1, NumSchedulers)), - NumSchedulers. - -worker_loop(Parent, Out) -> - Options = [report_errors, report_warnings, debug_info, {outdir, Out}], - erlang:send(Parent, {work_please, self()}), - receive - {module, Module} -> - log({compiling, Module}), - case compile:file(Module, Options) of - {ok, ModuleName} -> - Beam = filename:join(Out, ModuleName) ++ ".beam", - Message = {compiled, Beam}, - log(Message), - erlang:send(Parent, Message); - error -> - log({failed, Module}), - erlang:send(Parent, failed) - end, - worker_loop(Parent, Out) - end. - -compile_elixir(Modules, Out) -> - Error = [ - "The program elixir was not found. Is it installed?", - $\n, - "Documentation for installing Elixir can be viewed here:", - $\n, - "https://elixir-lang.org/install.html" - ], - case Modules of - [] -> {true, []}; - _ -> - log({starting, "compiler.app"}), - ok = application:start(compiler), - log({starting, "elixir.app"}), - case application:start(elixir) of - ok -> do_compile_elixir(Modules, Out); - _ -> - io:put_chars(standard_error, [Error, $\n]), - {false, []} - end - end. - -do_compile_elixir(Modules, Out) -> - ModuleBins = lists:map(fun(Module) -> - log({compiling, Module}), - list_to_binary(Module) - end, Modules), - OutBin = list_to_binary(Out), - Options = [{dest, OutBin}], - % Silence "redefining module" warnings. - % Compiled modules in the build directory are added to the code path. - % These warnings result from recompiling loaded modules. - % TODO: This line can likely be removed if/when the build directory is cleaned before every compilation. - 'Elixir.Code':compiler_options([{ignore_module_conflict, true}]), - case 'Elixir.Kernel.ParallelCompiler':compile_to_path(ModuleBins, OutBin, Options) of - {ok, ModuleAtoms, _} -> - ToBeam = fun(ModuleAtom) -> - Beam = filename:join(Out, atom_to_list(ModuleAtom)) ++ ".beam", - log({compiled, Beam}), - Beam - end, - {true, lists:map(ToBeam, ModuleAtoms)}; - {error, Errors, _} -> - % Log all filenames associated with modules that failed to compile. - % Note: The compiler prints compilation errors upon encountering them. - ErrorFiles = lists:usort([File || {File, _, _} <- Errors]), - Log = fun(File) -> - log({failed, binary_to_list(File)}) - end, - lists:foreach(Log, ErrorFiles), - {false, []}; - _ -> {false, []} - end. - -add_lib_to_erlang_path(Lib) -> - code:add_paths(filelib:wildcard([Lib, "/*/ebin"])). - -del_lib_from_erlang_path(Lib) -> - code:del_paths(filelib:wildcard([Lib, "/*/ebin"])). - -configure_logging() -> - Enabled = os:getenv("GLEAM_LOG") /= false, - persistent_term:put(gleam_logging_enabled, Enabled). - -log(Term) -> - case persistent_term:get(gleam_logging_enabled) of - true -> erlang:display(Term), ok; - false -> ok - end. diff --git a/test-output/cases/echo_list/build/dev/erlang/echo_list/_gleam_artefacts/main.cache b/test-output/cases/echo_list/build/dev/erlang/echo_list/_gleam_artefacts/main.cache deleted file mode 100644 index b594862cbe6..00000000000 Binary files a/test-output/cases/echo_list/build/dev/erlang/echo_list/_gleam_artefacts/main.cache and /dev/null differ diff --git a/test-output/cases/echo_list/build/dev/erlang/echo_list/_gleam_artefacts/main.cache_meta b/test-output/cases/echo_list/build/dev/erlang/echo_list/_gleam_artefacts/main.cache_meta deleted file mode 100644 index c4388b108ee..00000000000 Binary files a/test-output/cases/echo_list/build/dev/erlang/echo_list/_gleam_artefacts/main.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_list/build/dev/erlang/echo_list/_gleam_artefacts/main.cache_warnings b/test-output/cases/echo_list/build/dev/erlang/echo_list/_gleam_artefacts/main.cache_warnings deleted file mode 100644 index 1b1cb4d44c5..00000000000 Binary files a/test-output/cases/echo_list/build/dev/erlang/echo_list/_gleam_artefacts/main.cache_warnings and /dev/null differ diff --git a/test-output/cases/echo_list/build/dev/erlang/echo_list/_gleam_artefacts/main.erl b/test-output/cases/echo_list/build/dev/erlang/echo_list/_gleam_artefacts/main.erl deleted file mode 100644 index bf605641ac3..00000000000 --- a/test-output/cases/echo_list/build/dev/erlang/echo_list/_gleam_artefacts/main.erl +++ /dev/null @@ -1,190 +0,0 @@ --module(main). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([main/0]). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_list/src/main.gleam", 1). --spec main() -> list(integer()). -main() -> - echo([], "src/main.gleam", 2), - echo([1, 2, 3], "src/main.gleam", 3). - --define(is_lowercase_char(X), (X > 96 andalso X < 123)). --define(is_underscore_char(X), (X == 95)). --define(is_digit_char(X), (X > 47 andalso X < 58)). --define(could_be_record(Tuple), - erlang:is_tuple(Tuple) andalso - erlang:is_atom(erlang:element(1, Tuple)) andalso - erlang:element(1, Tuple) =/= false andalso - erlang:element(1, Tuple) =/= true andalso - erlang:element(1, Tuple) =/= nil -). --define(is_atom_char(C), - (?is_lowercase_char(C) orelse - ?is_underscore_char(C) orelse - ?is_digit_char(C)) -). - --define(grey, "\e[90m"). --define(reset_color, "\e[39m"). - -echo(Value, File, Line) -> - StringLine = erlang:integer_to_list(Line), - StringValue = echo@inspect(Value), - io:put_chars( - standard_error, - [?grey, File, $:, StringLine, ?reset_color, $\n, StringValue, $\n] - ), - Value. - -echo@inspect(Value) -> - case Value of - nil -> "Nil"; - true -> "True"; - false -> "False"; - Int when erlang:is_integer(Int) -> erlang:integer_to_list(Int); - Float when erlang:is_float(Float) -> io_lib_format:fwrite_g(Float); - Binary when erlang:is_binary(Binary) -> inspect@binary(Binary); - Bits when erlang:is_bitstring(Bits) -> inspect@bit_array(Bits); - Atom when erlang:is_atom(Atom) -> inspect@atom(Atom); - List when erlang:is_list(List) -> inspect@list(List); - Map when erlang:is_map(Map) -> inspect@map(Map); - Record when ?could_be_record(Record) -> inspect@record(Record); - Tuple when erlang:is_tuple(Tuple) -> inspect@tuple(Tuple); - Function when erlang:is_function(Function) -> inspect@function(Function); - Any -> ["//erl(", io_lib:format("~p", [Any]), ")"] - end. - -inspect@bit_array(Bits) -> - Pieces = inspect@bit_array_pieces(Bits, []), - Inner = lists:join(", ", lists:reverse(Pieces)), - ["<<", Inner, ">>"]. - -inspect@bit_array_pieces(Bits, Acc) -> - case Bits of - <<>> -> - Acc; - <> -> - inspect@bit_array_pieces(Rest, [erlang:integer_to_binary(Byte) | Acc]); - _ -> - Size = erlang:bit_size(Bits), - <> = Bits, - SizeString = [":size(", erlang:integer_to_binary(Size), ")"], - Piece = [erlang:integer_to_binary(RemainingBits), SizeString], - [Piece | Acc] - end. - -inspect@binary(Binary) -> - case inspect@maybe_utf8_string(Binary, <<>>) of - {ok, InspectedUtf8String} -> - InspectedUtf8String; - {error, not_a_utf8_string} -> - Segments = [erlang:integer_to_list(X) || <> <= Binary], - ["<<", lists:join(", ", Segments), ">>"] - end. - -inspect@atom(Atom) -> - Binary = erlang:atom_to_binary(Atom), - case inspect@maybe_gleam_atom(Binary, none, <<>>) of - {ok, Inspected} -> Inspected; - {error, _} -> ["atom.create_from_string(\"", Binary, "\")"] - end. - -inspect@list(List) -> - case inspect@proper_or_improper_list(List) of - {proper, Elements} -> ["[", Elements, "]"]; - {improper, Elements} -> ["//erl([", Elements, "])"] - end. - -inspect@map(Map) -> - Fields = [ - [<<"#(">>, echo@inspect(Key), <<", ">>, echo@inspect(Value), <<")">>] - || {Key, Value} <- maps:to_list(Map) - ], - ["dict.from_list([", lists:join(", ", Fields), "])"]. - -inspect@record(Record) -> - [Atom | ArgsList] = erlang:tuple_to_list(Record), - Args = lists:join(", ", lists:map(fun echo@inspect/1, ArgsList)), - [echo@inspect(Atom), "(", Args, ")"]. - -inspect@tuple(Tuple) -> - Elements = lists:map(fun echo@inspect/1, erlang:tuple_to_list(Tuple)), - ["#(", lists:join(", ", Elements), ")"]. - -inspect@function(Function) -> - {arity, Arity} = erlang:fun_info(Function, arity), - ArgsAsciiCodes = lists:seq($a, $a + Arity - 1), - Args = lists:join(", ", lists:map(fun(Arg) -> <> end, ArgsAsciiCodes)), - ["//fn(", Args, ") { ... }"]. - -inspect@maybe_utf8_string(Binary, Acc) -> - case Binary of - <<>> -> - {ok, <<$", Acc/binary, $">>}; - <> -> - Escaped = inspect@escape_grapheme(First), - inspect@maybe_utf8_string(Rest, <>); - _ -> - {error, not_a_utf8_string} - end. - -inspect@escape_grapheme(Char) -> - case Char of - $" -> <<$\\, $">>; - $\\ -> <<$\\, $\\>>; - $\r -> <<$\\, $r>>; - $\n -> <<$\\, $n>>; - $\t -> <<$\\, $t>>; - $\f -> <<$\\, $f>>; - X when X > 126, X < 160 -> inspect@convert_to_u(X); - X when X < 32 -> inspect@convert_to_u(X); - Other -> <> - end. - -inspect@convert_to_u(Code) -> - erlang:list_to_binary(io_lib:format("\\u{~4.16.0B}", [Code])). - -inspect@proper_or_improper_list(List) -> - case List of - [] -> - {proper, []}; - [First] -> - {proper, [echo@inspect(First)]}; - [First | Rest] when erlang:is_list(Rest) -> - {Kind, Inspected} = inspect@proper_or_improper_list(Rest), - {Kind, [echo@inspect(First), ", " | Inspected]}; - [First | ImproperRest] -> - {improper, [echo@inspect(First), " | ", echo@inspect(ImproperRest)]} - end. - -inspect@maybe_gleam_atom(Atom, PrevChar, Acc) -> - case {Atom, PrevChar} of - {<<>>, none} -> - {error, nil}; - {<>, none} when ?is_digit_char(First) -> - {error, nil}; - {<<"_", _/binary>>, none} -> - {error, nil}; - {<<"_">>, _} -> - {error, nil}; - {<<"_", _/binary>>, $_} -> - {error, nil}; - {<>, _} when not ?is_atom_char(First) -> - {error, nil}; - {<>, none} -> - inspect@maybe_gleam_atom(Rest, First, <>); - {<<"_", Rest/binary>>, _} -> - inspect@maybe_gleam_atom(Rest, $_, Acc); - {<>, $_} -> - inspect@maybe_gleam_atom(Rest, First, <>); - {<>, _} -> - inspect@maybe_gleam_atom(Rest, First, <>); - {<<>>, _} -> - {ok, Acc}; - _ -> - erlang:throw({gleam_error, echo, Atom, PrevChar, Acc}) - end. - -inspect@uppercase(X) -> X - 32. - diff --git a/test-output/cases/echo_list/build/dev/erlang/echo_list/ebin/echo_list.app b/test-output/cases/echo_list/build/dev/erlang/echo_list/ebin/echo_list.app deleted file mode 100644 index 18c392780e8..00000000000 --- a/test-output/cases/echo_list/build/dev/erlang/echo_list/ebin/echo_list.app +++ /dev/null @@ -1,7 +0,0 @@ -{application, echo_list, [ - {vsn, "1.0.0"}, - {applications, []}, - {description, ""}, - {modules, [main]}, - {registered, []} -]}. diff --git a/test-output/cases/echo_list/build/dev/erlang/gleam_version b/test-output/cases/echo_list/build/dev/erlang/gleam_version deleted file mode 100644 index 3e1ad720b13..00000000000 --- a/test-output/cases/echo_list/build/dev/erlang/gleam_version +++ /dev/null @@ -1 +0,0 @@ -1.5.0 \ No newline at end of file diff --git a/test-output/cases/echo_list/build/dev/javascript/echo_list/_gleam_artefacts/main.cache b/test-output/cases/echo_list/build/dev/javascript/echo_list/_gleam_artefacts/main.cache deleted file mode 100644 index 46ec0fafa6c..00000000000 Binary files a/test-output/cases/echo_list/build/dev/javascript/echo_list/_gleam_artefacts/main.cache and /dev/null differ diff --git a/test-output/cases/echo_list/build/dev/javascript/echo_list/_gleam_artefacts/main.cache_meta b/test-output/cases/echo_list/build/dev/javascript/echo_list/_gleam_artefacts/main.cache_meta deleted file mode 100644 index c4388b108ee..00000000000 Binary files a/test-output/cases/echo_list/build/dev/javascript/echo_list/_gleam_artefacts/main.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_list/build/dev/javascript/echo_list/_gleam_artefacts/main.cache_warnings b/test-output/cases/echo_list/build/dev/javascript/echo_list/_gleam_artefacts/main.cache_warnings deleted file mode 100644 index 1b1cb4d44c5..00000000000 Binary files a/test-output/cases/echo_list/build/dev/javascript/echo_list/_gleam_artefacts/main.cache_warnings and /dev/null differ diff --git a/test-output/cases/echo_list/build/dev/javascript/echo_list/gleam.main.mjs b/test-output/cases/echo_list/build/dev/javascript/echo_list/gleam.main.mjs deleted file mode 100644 index e230911e646..00000000000 --- a/test-output/cases/echo_list/build/dev/javascript/echo_list/gleam.main.mjs +++ /dev/null @@ -1,2 +0,0 @@ -import { main } from "./main.mjs"; -main(); diff --git a/test-output/cases/echo_list/build/dev/javascript/echo_list/gleam.mjs b/test-output/cases/echo_list/build/dev/javascript/echo_list/gleam.mjs deleted file mode 100644 index 197cbbc35d4..00000000000 --- a/test-output/cases/echo_list/build/dev/javascript/echo_list/gleam.mjs +++ /dev/null @@ -1 +0,0 @@ -export * from "../prelude.mjs"; diff --git a/test-output/cases/echo_list/build/dev/javascript/echo_list/main.mjs b/test-output/cases/echo_list/build/dev/javascript/echo_list/main.mjs deleted file mode 100644 index a2462f7602f..00000000000 --- a/test-output/cases/echo_list/build/dev/javascript/echo_list/main.mjs +++ /dev/null @@ -1,129 +0,0 @@ -import { - toList, - BitArray as $BitArray, - List as $List, - UtfCodepoint as $UtfCodepoint, - CustomType as $CustomType, -} from "./gleam.mjs"; - -export function main() { - echo(toList([]), "src/main.gleam", 2); - return echo(toList([1, 2, 3]), "src/main.gleam", 3); -} - -function echo(value, file, line) { - const grey = "\u001b[90m"; - const reset_color = "\u001b[39m"; - const file_line = `${file}:${line}`; - const string_value = echo$inspect(value); - - if (typeof process === "object" && process.stderr?.write) { - // If we're in Node.js, use `stderr` - const string = `${grey}${file_line}${reset_color}\n${string_value}\n`; - process.stderr.write(string); - } else if (typeof Deno === "object") { - // If we're in Deno, use `stderr` - const string = `${grey}${file_line}${reset_color}\n${string_value}\n`; - Deno.stderr.writeSync(new TextEncoder().encode(string)); - } else { - // Otherwise, use `console.log` - // The browser's console.log doesn't support ansi escape codes - const string = `${file_line}\n${string_value}`; - console.log(string); - } - - return value; -} - -function echo$inspectString(str) { - let new_str = '"'; - for (let i = 0; i < str.length; i++) { - let char = str[i]; - if (char == "\n") new_str += "\\n"; - else if (char == "\r") new_str += "\\r"; - else if (char == "\t") new_str += "\\t"; - else if (char == "\f") new_str += "\\f"; - else if (char == "\\") new_str += "\\\\"; - else if (char == '"') new_str += '\\"'; - else if (char < " " || (char > "~" && char < "\u{00A0}")) { - new_str += "\\u{" + char.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0") + "}"; - } else { - new_str += char; - } - } - new_str += '"'; - return new_str; -} - -function echo$inspectDict(map) { - let body = "dict.from_list(["; - let first = true; - map.forEach((value, key) => { - if (!first) body = body + ", "; - body = body + "#(" + echo$inspect(key) + ", " + echo$inspect(value) + ")"; - first = false; - }); - return body + "])"; -} - -function echo$inspectCustomType(record) { - const props = Object.keys(record) - .map((label) => { - const value = echo$inspect(record[label]); - return isNaN(parseInt(label)) ? `${label}: ${value}` : value; - }) - .join(", "); - return props ? `${record.constructor.name}(${props})` : record.constructor.name; -} - -function echo$inspectObject(v) { - const name = Object.getPrototypeOf(v)?.constructor?.name || "Object"; - const props = []; - for (const k of Object.keys(v)) { - props.push(`${echo$inspect(k)}: ${echo$inspect(v[k])}`); - } - const body = props.length ? " " + props.join(", ") + " " : ""; - const head = name === "Object" ? "" : name + " "; - return `//js(${head}{${body}})`; -} - -function echo$inspect(v) { - const t = typeof v; - if (v === true) return "True"; - if (v === false) return "False"; - if (v === null) return "//js(null)"; - if (v === undefined) return "Nil"; - if (t === "string") return echo$inspectString(v); - if (t === "bigint" || t === "number") return v.toString(); - if (Array.isArray(v)) return `#(${v.map(echo$inspect).join(", ")})`; - if (v instanceof $List) return `[${v.toArray().map(echo$inspect).join(", ")}]`; - if (v instanceof $UtfCodepoint) return `//utfcodepoint(${String.fromCodePoint(v.value)})`; - if (v instanceof $BitArray) return `<<${Array.from(v.buffer).join(", ")}>>`; - if (v instanceof $CustomType) return echo$inspectCustomType(v); - if (echo$isDict(v)) return echo$inspectDict(v); - if (v instanceof Set) return `//js(Set(${[...v].map(echo$inspect).join(", ")}))`; - if (v instanceof RegExp) return `//js(${v})`; - if (v instanceof Date) return `//js(Date("${v.toISOString()}"))`; - if (v instanceof Function) { - const args = []; - for (const i of Array(v.length).keys()) args.push(String.fromCharCode(i + 97)); - return `//fn(${args.join(", ")}) { ... }`; - } - return echo$inspectObject(v); -} - -function echo$isDict(value) { - try { - // We can only check if an object is a stdlib Dict if it is one of the - // project's dependencies. - // The `Dict` class is the default export of `stdlib/dict.mjs` - // that we import as `$stdlib$dict`. - return value instanceof $stdlib$dict.default; - } catch { - // If stdlib is not one of the project's dependencies then `$stdlib$dict` - // will not have been imported and the check will throw an exception meaning - // we can't check if something is actually a `Dict`. - return false; - } -} - diff --git a/test-output/cases/echo_list/build/dev/javascript/gleam_version b/test-output/cases/echo_list/build/dev/javascript/gleam_version deleted file mode 100644 index 3e1ad720b13..00000000000 --- a/test-output/cases/echo_list/build/dev/javascript/gleam_version +++ /dev/null @@ -1 +0,0 @@ -1.5.0 \ No newline at end of file diff --git a/test-output/cases/echo_list/build/dev/javascript/prelude.mjs b/test-output/cases/echo_list/build/dev/javascript/prelude.mjs deleted file mode 100644 index d2adeef273f..00000000000 --- a/test-output/cases/echo_list/build/dev/javascript/prelude.mjs +++ /dev/null @@ -1,455 +0,0 @@ -// Values marked with @internal are not part of the public API and may change -// without notice. - -export class CustomType { - withFields(fields) { - let properties = Object.keys(this).map((label) => - label in fields ? fields[label] : this[label], - ); - return new this.constructor(...properties); - } -} - -export class List { - static fromArray(array, tail) { - let t = tail || new Empty(); - for (let i = array.length - 1; i >= 0; --i) { - t = new NonEmpty(array[i], t); - } - return t; - } - - [Symbol.iterator]() { - return new ListIterator(this); - } - - toArray() { - return [...this]; - } - - // @internal - atLeastLength(desired) { - for (let _ of this) { - if (desired <= 0) return true; - desired--; - } - return desired <= 0; - } - - // @internal - hasLength(desired) { - for (let _ of this) { - if (desired <= 0) return false; - desired--; - } - return desired === 0; - } - - // @internal - countLength() { - let length = 0; - for (let _ of this) length++; - return length; - } -} - -// @internal -export function prepend(element, tail) { - return new NonEmpty(element, tail); -} - -export function toList(elements, tail) { - return List.fromArray(elements, tail); -} - -// @internal -class ListIterator { - #current; - - constructor(current) { - this.#current = current; - } - - next() { - if (this.#current instanceof Empty) { - return { done: true }; - } else { - let { head, tail } = this.#current; - this.#current = tail; - return { value: head, done: false }; - } - } -} - -export class Empty extends List {} - -export class NonEmpty extends List { - constructor(head, tail) { - super(); - this.head = head; - this.tail = tail; - } -} - -export class BitArray { - constructor(buffer) { - if (!(buffer instanceof Uint8Array)) { - throw "BitArray can only be constructed from a Uint8Array"; - } - this.buffer = buffer; - } - - // @internal - get length() { - return this.buffer.length; - } - - // @internal - byteAt(index) { - return this.buffer[index]; - } - - // @internal - floatFromSlice(start, end, isBigEndian) { - return byteArrayToFloat(this.buffer, start, end, isBigEndian); - } - - // @internal - intFromSlice(start, end, isBigEndian, isSigned) { - return byteArrayToInt(this.buffer, start, end, isBigEndian, isSigned); - } - - // @internal - binaryFromSlice(start, end) { - return new BitArray(this.buffer.slice(start, end)); - } - - // @internal - sliceAfter(index) { - return new BitArray(this.buffer.slice(index)); - } -} - -export class UtfCodepoint { - constructor(value) { - this.value = value; - } -} - -// @internal -export function toBitArray(segments) { - if (segments.length === 0) { - return new BitArray(new Uint8Array()); - } - - if (segments.length === 1) { - // When there is a single Uint8Array segment, pass it directly to the bit - // array constructor to avoid a copy - if (segments[0] instanceof Uint8Array) { - return new BitArray(segments[0]); - } - - return new BitArray(new Uint8Array(segments)); - } - - // Count the total number of bytes, and check if there are any Uint8Array - // segments - let bytes = 0; - let hasUint8ArraySegment = false; - for (const segment of segments) { - if (segment instanceof Uint8Array) { - bytes += segment.byteLength; - hasUint8ArraySegment = true; - } else { - bytes++; - } - } - - // If there aren't any Uint8Array segments then pass the segments array - // directly to the Uint8Array constructor - if (!hasUint8ArraySegment) { - return new BitArray(new Uint8Array(segments)); - } - - // Copy the segments into a Uint8Array - let u8Array = new Uint8Array(bytes); - let cursor = 0; - for (let segment of segments) { - if (segment instanceof Uint8Array) { - u8Array.set(segment, cursor); - cursor += segment.byteLength; - } else { - u8Array[cursor] = segment; - cursor++; - } - } - - return new BitArray(u8Array); -} - -// @internal -// Derived from this answer https://stackoverflow.com/questions/8482309/converting-javascript-integer-to-byte-array-and-back -export function sizedInt(value, size, isBigEndian) { - if (size < 0) { - return new Uint8Array(); - } - if (size % 8 != 0) { - const msg = `Bit arrays must be byte aligned on JavaScript, got size of ${size} bits`; - throw new globalThis.Error(msg); - } - - const byteArray = new Uint8Array(size / 8); - - // Convert negative number to two's complement representation - if (value < 0) { - value = 2 ** size + value; - } - - if (isBigEndian) { - for (let i = byteArray.length - 1; i >= 0; i--) { - const byte = value % 256; - byteArray[i] = byte; - value = (value - byte) / 256; - } - } else { - for (let i = 0; i < byteArray.length; i++) { - const byte = value % 256; - byteArray[i] = byte; - value = (value - byte) / 256; - } - } - - return byteArray; -} - -// @internal -export function byteArrayToInt(byteArray, start, end, isBigEndian, isSigned) { - let value = 0; - - // Read bytes as an unsigned integer value - if (isBigEndian) { - for (let i = start; i < end; i++) { - value = value * 256 + byteArray[i]; - } - } else { - for (let i = end - 1; i >= start; i--) { - value = value * 256 + byteArray[i]; - } - } - - if (isSigned) { - const byteSize = end - start; - - const highBit = 2 ** (byteSize * 8 - 1); - - // If the high bit is set and this is a signed integer, reinterpret as - // two's complement - if (value >= highBit) { - value -= highBit * 2; - } - } - - return value; -} - -// @internal -export function byteArrayToFloat(byteArray, start, end, isBigEndian) { - const view = new DataView(byteArray.buffer); - - const byteSize = end - start; - - if (byteSize === 8) { - return view.getFloat64(start, !isBigEndian); - } else if (byteSize === 4) { - return view.getFloat32(start, !isBigEndian); - } else { - const msg = `Sized floats must be 32-bit or 64-bit on JavaScript, got size of ${byteSize * 8} bits`; - throw new globalThis.Error(msg); - } -} - -// @internal -export function stringBits(string) { - return new TextEncoder().encode(string); -} - -// @internal -export function codepointBits(codepoint) { - return stringBits(String.fromCodePoint(codepoint.value)); -} - -// @internal -export function sizedFloat(float, size, isBigEndian) { - if (size !== 32 && size !== 64) { - const msg = `Sized floats must be 32-bit or 64-bit on JavaScript, got size of ${size} bits`; - throw new globalThis.Error(msg); - } - - const byteArray = new Uint8Array(size / 8); - - const view = new DataView(byteArray.buffer); - - if (size == 64) { - view.setFloat64(0, float, !isBigEndian); - } else if (size === 32) { - view.setFloat32(0, float, !isBigEndian); - } - - return byteArray; -} - -export class Result extends CustomType { - // @internal - static isResult(data) { - return data instanceof Result; - } -} - -export class Ok extends Result { - constructor(value) { - super(); - this[0] = value; - } - - // @internal - isOk() { - return true; - } -} - -export class Error extends Result { - constructor(detail) { - super(); - this[0] = detail; - } - - // @internal - isOk() { - return false; - } -} - -export function isEqual(x, y) { - let values = [x, y]; - - while (values.length) { - let a = values.pop(); - let b = values.pop(); - if (a === b) continue; - - if (!isObject(a) || !isObject(b)) return false; - let unequal = - !structurallyCompatibleObjects(a, b) || - unequalDates(a, b) || - unequalBuffers(a, b) || - unequalArrays(a, b) || - unequalMaps(a, b) || - unequalSets(a, b) || - unequalRegExps(a, b); - if (unequal) return false; - - const proto = Object.getPrototypeOf(a); - if (proto !== null && typeof proto.equals === "function") { - try { - if (a.equals(b)) continue; - else return false; - } catch {} - } - - let [keys, get] = getters(a); - for (let k of keys(a)) { - values.push(get(a, k), get(b, k)); - } - } - - return true; -} - -function getters(object) { - if (object instanceof Map) { - return [(x) => x.keys(), (x, y) => x.get(y)]; - } else { - let extra = object instanceof globalThis.Error ? ["message"] : []; - return [(x) => [...extra, ...Object.keys(x)], (x, y) => x[y]]; - } -} - -function unequalDates(a, b) { - return a instanceof Date && (a > b || a < b); -} - -function unequalBuffers(a, b) { - return ( - a.buffer instanceof ArrayBuffer && - a.BYTES_PER_ELEMENT && - !(a.byteLength === b.byteLength && a.every((n, i) => n === b[i])) - ); -} - -function unequalArrays(a, b) { - return Array.isArray(a) && a.length !== b.length; -} - -function unequalMaps(a, b) { - return a instanceof Map && a.size !== b.size; -} - -function unequalSets(a, b) { - return ( - a instanceof Set && (a.size != b.size || [...a].some((e) => !b.has(e))) - ); -} - -function unequalRegExps(a, b) { - return a instanceof RegExp && (a.source !== b.source || a.flags !== b.flags); -} - -function isObject(a) { - return typeof a === "object" && a !== null; -} - -function structurallyCompatibleObjects(a, b) { - if (typeof a !== "object" && typeof b !== "object" && (!a || !b)) - return false; - - let nonstructural = [Promise, WeakSet, WeakMap, Function]; - if (nonstructural.some((c) => a instanceof c)) return false; - - return a.constructor === b.constructor; -} - -// @internal -export function remainderInt(a, b) { - if (b === 0) { - return 0; - } else { - return a % b; - } -} - -// @internal -export function divideInt(a, b) { - return Math.trunc(divideFloat(a, b)); -} - -// @internal -export function divideFloat(a, b) { - if (b === 0) { - return 0; - } else { - return a / b; - } -} - -// @internal -export function makeError(variant, module, line, fn, message, extra) { - let error = new globalThis.Error(message); - error.gleam_error = variant; - error.module = module; - error.line = line; - error.function = fn; - // TODO: Remove this with Gleam v2.0.0 - error.fn = fn; - for (let k in extra) error[k] = extra[k]; - return error; -} diff --git a/test-output/cases/echo_list/build/packages/packages.toml b/test-output/cases/echo_list/build/packages/packages.toml deleted file mode 100644 index e74c18552bb..00000000000 --- a/test-output/cases/echo_list/build/packages/packages.toml +++ /dev/null @@ -1 +0,0 @@ -[packages] diff --git a/test-output/cases/echo_list/manifest.toml b/test-output/cases/echo_list/manifest.toml deleted file mode 100644 index c5d779a3f81..00000000000 --- a/test-output/cases/echo_list/manifest.toml +++ /dev/null @@ -1,7 +0,0 @@ -# This file was generated by Gleam -# You typically do not need to edit this file - -packages = [ -] - -[requirements] diff --git a/test-output/cases/echo_nil/build/dev/erlang/echo_nil/_gleam_artefacts/echo_nil@@main.erl b/test-output/cases/echo_nil/build/dev/erlang/echo_nil/_gleam_artefacts/echo_nil@@main.erl deleted file mode 100644 index 6dfa31292d3..00000000000 --- a/test-output/cases/echo_nil/build/dev/erlang/echo_nil/_gleam_artefacts/echo_nil@@main.erl +++ /dev/null @@ -1,99 +0,0 @@ --module('echo_nil@@main'). --export([run/1]). - --define(red, "\e[31;1m"). --define(grey, "\e[90m"). --define(reset_color, "\e[39m"). --define(reset_all, "\e[0m"). - -run(Module) -> - io:setopts(standard_io, [binary, {encoding, utf8}]), - io:setopts(standard_error, [{encoding, utf8}]), - process_flag(trap_exit, true), - Pid = spawn_link(fun() -> run_module(Module) end), - receive - {'EXIT', Pid, {Reason, StackTrace}} -> - print_error(exit, Reason, StackTrace), - init:stop(1) - end. - -run_module(Module) -> - try - {ok, _} = application:ensure_all_started('echo_nil'), - erlang:process_flag(trap_exit, false), - Module:main(), - erlang:halt(0) - catch - Class:Reason:StackTrace -> - print_error(Class, Reason, StackTrace), - init:stop(1) - end. - -print_error(Class, Error, Stacktrace) -> - Printed = [ - ?red, "runtime error", ?reset_color, ": ", error_class(Class, Error), ?reset_all, - "\n\n", - error_message(Error), - "\n\n", - error_details(Class, Error), - "stacktrace:\n", - [error_frame(Line) || Line <- refine_first(Error, Stacktrace)] - ], - io:format(standard_error, "~ts~n", [Printed]). - -refine_first(#{gleam_error := _, line := L}, [{M, F, A, [{file, Fi} | _]} | S]) -> - [{M, F, A, [{file, Fi}, {line, L}]} | S]; -refine_first(_, S) -> - S. - -error_class(_, #{gleam_error := panic}) -> "panic"; -error_class(_, #{gleam_error := todo}) -> "todo"; -error_class(_, #{gleam_error := let_assert}) -> "let assert"; -error_class(Class, _) -> ["Erlang ", atom_to_binary(Class)]. - -error_message(#{gleam_error := _, message := M}) -> - M; -error_message(undef) -> - <<"A function was called but it did not exist."/utf8 >>; -error_message({case_clause, _}) -> - <<"No pattern matched in an Erlang case expression."/utf8>>; -error_message({badmatch, _}) -> - <<"An Erlang assignment pattern did not match."/utf8>>; -error_message(function_clause) -> - <<"No Erlang function clause matched the arguments it was called with."/utf8>>; -error_message(_) -> - <<"An error occurred outside of Gleam."/utf8>>. - -error_details(_, #{gleam_error := let_assert, value := V}) -> - ["unmatched value:\n ", print_term(V), $\n, $\n]; -error_details(_, {case_clause, V}) -> - ["unmatched value:\n ", print_term(V), $\n, $\n]; -error_details(_, {badmatch, V}) -> - ["unmatched value:\n ", print_term(V), $\n, $\n]; -error_details(_, #{gleam_error := _}) -> - []; -error_details(error, function_clause) -> - []; -error_details(error, undef) -> - []; -error_details(C, E) -> - ["erlang:", atom_to_binary(C), $(, print_term(E), $), $\n, $\n]. - -print_term(T) -> - try - gleam@string:inspect(T) - catch - _:_ -> io_lib:format("~p", [T]) - end. - -error_frame({?MODULE, _, _, _}) -> []; -error_frame({erl_eval, _, _, _}) -> []; -error_frame({init, _, _, _}) -> []; -error_frame({M, F, _, O}) -> - M1 = string:replace(atom_to_binary(M), "@", "/", all), - [" ", M1, $., atom_to_binary(F), error_frame_end(O), $\n]. - -error_frame_end([{file, Fi}, {line, L} | _]) -> - [?grey, $\s, Fi, $:, integer_to_binary(L), ?reset_all]; -error_frame_end(_) -> - [?grey, " unknown source", ?reset_all]. \ No newline at end of file diff --git a/test-output/cases/echo_nil/build/dev/erlang/echo_nil/_gleam_artefacts/gleam@@compile.erl b/test-output/cases/echo_nil/build/dev/erlang/echo_nil/_gleam_artefacts/gleam@@compile.erl deleted file mode 100644 index 3e0a645b737..00000000000 --- a/test-output/cases/echo_nil/build/dev/erlang/echo_nil/_gleam_artefacts/gleam@@compile.erl +++ /dev/null @@ -1,163 +0,0 @@ -#!/usr/bin/env escript --mode(compile). - -% TODO: Don't concurrently print warnings and errors -% TODO: Some tests - -main(_) -> compile_package_loop(). - -compile_package_loop() -> - case file:read_line(standard_io) of - eof -> ok; - {ok, Line} -> - Chars = unicode:characters_to_list(Line), - {ok, Tokens, _} = erl_scan:string(Chars), - {ok, {Lib, Out, Modules}} = erl_parse:parse_term(Tokens), - case compile_package(Lib, Out, Modules) of - ok -> io:put_chars("gleam-compile-result-ok\n"); - err -> io:put_chars("gleam-compile-result-error\n") - end, - compile_package_loop() - end. - -compile_package(Lib, Out, Modules) -> - IsElixirModule = fun(Module) -> - filename:extension(Module) =:= ".ex" - end, - {ElixirModules, ErlangModules} = lists:partition(IsElixirModule, Modules), - ok = configure_logging(), - ok = add_lib_to_erlang_path(Lib), - ok = filelib:ensure_dir([Out, $/]), - {ErlangOk, _ErlangBeams} = compile_erlang(ErlangModules, Out), - {ElixirOk, _ElixirBeams} = case ErlangOk of - true -> compile_elixir(ElixirModules, Out); - false -> {false, []} - end, - ok = del_lib_from_erlang_path(Lib), - case ErlangOk and ElixirOk of - true -> ok; - false -> err - end. - -compile_erlang(Modules, Out) -> - Workers = start_compiler_workers(Out), - ok = producer_loop(Modules, Workers), - collect_results({true, []}). - -collect_results(Acc = {Result, Beams}) -> - receive - {compiled, Beam} -> collect_results({Result, [Beam | Beams]}); - failed -> collect_results({false, Beams}) - after 0 -> Acc - end. - -producer_loop([], 0) -> - ok; -producer_loop([], Workers) -> - receive - {work_please, _} -> producer_loop([], Workers - 1) - end; -producer_loop([Module | Modules], Workers) -> - receive - {work_please, Worker} -> - erlang:send(Worker, {module, Module}), - producer_loop(Modules, Workers) - end. - -start_compiler_workers(Out) -> - Parent = self(), - NumSchedulers = erlang:system_info(schedulers), - SpawnWorker = fun(_) -> - erlang:spawn_link(fun() -> worker_loop(Parent, Out) end) - end, - lists:foreach(SpawnWorker, lists:seq(1, NumSchedulers)), - NumSchedulers. - -worker_loop(Parent, Out) -> - Options = [report_errors, report_warnings, debug_info, {outdir, Out}], - erlang:send(Parent, {work_please, self()}), - receive - {module, Module} -> - log({compiling, Module}), - case compile:file(Module, Options) of - {ok, ModuleName} -> - Beam = filename:join(Out, ModuleName) ++ ".beam", - Message = {compiled, Beam}, - log(Message), - erlang:send(Parent, Message); - error -> - log({failed, Module}), - erlang:send(Parent, failed) - end, - worker_loop(Parent, Out) - end. - -compile_elixir(Modules, Out) -> - Error = [ - "The program elixir was not found. Is it installed?", - $\n, - "Documentation for installing Elixir can be viewed here:", - $\n, - "https://elixir-lang.org/install.html" - ], - case Modules of - [] -> {true, []}; - _ -> - log({starting, "compiler.app"}), - ok = application:start(compiler), - log({starting, "elixir.app"}), - case application:start(elixir) of - ok -> do_compile_elixir(Modules, Out); - _ -> - io:put_chars(standard_error, [Error, $\n]), - {false, []} - end - end. - -do_compile_elixir(Modules, Out) -> - ModuleBins = lists:map(fun(Module) -> - log({compiling, Module}), - list_to_binary(Module) - end, Modules), - OutBin = list_to_binary(Out), - Options = [{dest, OutBin}], - % Silence "redefining module" warnings. - % Compiled modules in the build directory are added to the code path. - % These warnings result from recompiling loaded modules. - % TODO: This line can likely be removed if/when the build directory is cleaned before every compilation. - 'Elixir.Code':compiler_options([{ignore_module_conflict, true}]), - case 'Elixir.Kernel.ParallelCompiler':compile_to_path(ModuleBins, OutBin, Options) of - {ok, ModuleAtoms, _} -> - ToBeam = fun(ModuleAtom) -> - Beam = filename:join(Out, atom_to_list(ModuleAtom)) ++ ".beam", - log({compiled, Beam}), - Beam - end, - {true, lists:map(ToBeam, ModuleAtoms)}; - {error, Errors, _} -> - % Log all filenames associated with modules that failed to compile. - % Note: The compiler prints compilation errors upon encountering them. - ErrorFiles = lists:usort([File || {File, _, _} <- Errors]), - Log = fun(File) -> - log({failed, binary_to_list(File)}) - end, - lists:foreach(Log, ErrorFiles), - {false, []}; - _ -> {false, []} - end. - -add_lib_to_erlang_path(Lib) -> - code:add_paths(filelib:wildcard([Lib, "/*/ebin"])). - -del_lib_from_erlang_path(Lib) -> - code:del_paths(filelib:wildcard([Lib, "/*/ebin"])). - -configure_logging() -> - Enabled = os:getenv("GLEAM_LOG") /= false, - persistent_term:put(gleam_logging_enabled, Enabled). - -log(Term) -> - case persistent_term:get(gleam_logging_enabled) of - true -> erlang:display(Term), ok; - false -> ok - end. diff --git a/test-output/cases/echo_nil/build/dev/erlang/echo_nil/_gleam_artefacts/main.cache b/test-output/cases/echo_nil/build/dev/erlang/echo_nil/_gleam_artefacts/main.cache deleted file mode 100644 index 0673516c856..00000000000 Binary files a/test-output/cases/echo_nil/build/dev/erlang/echo_nil/_gleam_artefacts/main.cache and /dev/null differ diff --git a/test-output/cases/echo_nil/build/dev/erlang/echo_nil/_gleam_artefacts/main.cache_meta b/test-output/cases/echo_nil/build/dev/erlang/echo_nil/_gleam_artefacts/main.cache_meta deleted file mode 100644 index 78ea6ee58dc..00000000000 Binary files a/test-output/cases/echo_nil/build/dev/erlang/echo_nil/_gleam_artefacts/main.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_nil/build/dev/erlang/echo_nil/_gleam_artefacts/main.cache_warnings b/test-output/cases/echo_nil/build/dev/erlang/echo_nil/_gleam_artefacts/main.cache_warnings deleted file mode 100644 index 1b1cb4d44c5..00000000000 Binary files a/test-output/cases/echo_nil/build/dev/erlang/echo_nil/_gleam_artefacts/main.cache_warnings and /dev/null differ diff --git a/test-output/cases/echo_nil/build/dev/erlang/echo_nil/_gleam_artefacts/main.erl b/test-output/cases/echo_nil/build/dev/erlang/echo_nil/_gleam_artefacts/main.erl deleted file mode 100644 index 1e02d8fcef5..00000000000 --- a/test-output/cases/echo_nil/build/dev/erlang/echo_nil/_gleam_artefacts/main.erl +++ /dev/null @@ -1,189 +0,0 @@ --module(main). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([main/0]). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_nil/src/main.gleam", 1). --spec main() -> nil. -main() -> - echo(nil, "src/main.gleam", 2). - --define(is_lowercase_char(X), (X > 96 andalso X < 123)). --define(is_underscore_char(X), (X == 95)). --define(is_digit_char(X), (X > 47 andalso X < 58)). --define(could_be_record(Tuple), - erlang:is_tuple(Tuple) andalso - erlang:is_atom(erlang:element(1, Tuple)) andalso - erlang:element(1, Tuple) =/= false andalso - erlang:element(1, Tuple) =/= true andalso - erlang:element(1, Tuple) =/= nil -). --define(is_atom_char(C), - (?is_lowercase_char(C) orelse - ?is_underscore_char(C) orelse - ?is_digit_char(C)) -). - --define(grey, "\e[90m"). --define(reset_color, "\e[39m"). - -echo(Value, File, Line) -> - StringLine = erlang:integer_to_list(Line), - StringValue = echo@inspect(Value), - io:put_chars( - standard_error, - [?grey, File, $:, StringLine, ?reset_color, $\n, StringValue, $\n] - ), - Value. - -echo@inspect(Value) -> - case Value of - nil -> "Nil"; - true -> "True"; - false -> "False"; - Int when erlang:is_integer(Int) -> erlang:integer_to_list(Int); - Float when erlang:is_float(Float) -> io_lib_format:fwrite_g(Float); - Binary when erlang:is_binary(Binary) -> inspect@binary(Binary); - Bits when erlang:is_bitstring(Bits) -> inspect@bit_array(Bits); - Atom when erlang:is_atom(Atom) -> inspect@atom(Atom); - List when erlang:is_list(List) -> inspect@list(List); - Map when erlang:is_map(Map) -> inspect@map(Map); - Record when ?could_be_record(Record) -> inspect@record(Record); - Tuple when erlang:is_tuple(Tuple) -> inspect@tuple(Tuple); - Function when erlang:is_function(Function) -> inspect@function(Function); - Any -> ["//erl(", io_lib:format("~p", [Any]), ")"] - end. - -inspect@bit_array(Bits) -> - Pieces = inspect@bit_array_pieces(Bits, []), - Inner = lists:join(", ", lists:reverse(Pieces)), - ["<<", Inner, ">>"]. - -inspect@bit_array_pieces(Bits, Acc) -> - case Bits of - <<>> -> - Acc; - <> -> - inspect@bit_array_pieces(Rest, [erlang:integer_to_binary(Byte) | Acc]); - _ -> - Size = erlang:bit_size(Bits), - <> = Bits, - SizeString = [":size(", erlang:integer_to_binary(Size), ")"], - Piece = [erlang:integer_to_binary(RemainingBits), SizeString], - [Piece | Acc] - end. - -inspect@binary(Binary) -> - case inspect@maybe_utf8_string(Binary, <<>>) of - {ok, InspectedUtf8String} -> - InspectedUtf8String; - {error, not_a_utf8_string} -> - Segments = [erlang:integer_to_list(X) || <> <= Binary], - ["<<", lists:join(", ", Segments), ">>"] - end. - -inspect@atom(Atom) -> - Binary = erlang:atom_to_binary(Atom), - case inspect@maybe_gleam_atom(Binary, none, <<>>) of - {ok, Inspected} -> Inspected; - {error, _} -> ["atom.create_from_string(\"", Binary, "\")"] - end. - -inspect@list(List) -> - case inspect@proper_or_improper_list(List) of - {proper, Elements} -> ["[", Elements, "]"]; - {improper, Elements} -> ["//erl([", Elements, "])"] - end. - -inspect@map(Map) -> - Fields = [ - [<<"#(">>, echo@inspect(Key), <<", ">>, echo@inspect(Value), <<")">>] - || {Key, Value} <- maps:to_list(Map) - ], - ["dict.from_list([", lists:join(", ", Fields), "])"]. - -inspect@record(Record) -> - [Atom | ArgsList] = erlang:tuple_to_list(Record), - Args = lists:join(", ", lists:map(fun echo@inspect/1, ArgsList)), - [echo@inspect(Atom), "(", Args, ")"]. - -inspect@tuple(Tuple) -> - Elements = lists:map(fun echo@inspect/1, erlang:tuple_to_list(Tuple)), - ["#(", lists:join(", ", Elements), ")"]. - -inspect@function(Function) -> - {arity, Arity} = erlang:fun_info(Function, arity), - ArgsAsciiCodes = lists:seq($a, $a + Arity - 1), - Args = lists:join(", ", lists:map(fun(Arg) -> <> end, ArgsAsciiCodes)), - ["//fn(", Args, ") { ... }"]. - -inspect@maybe_utf8_string(Binary, Acc) -> - case Binary of - <<>> -> - {ok, <<$", Acc/binary, $">>}; - <> -> - Escaped = inspect@escape_grapheme(First), - inspect@maybe_utf8_string(Rest, <>); - _ -> - {error, not_a_utf8_string} - end. - -inspect@escape_grapheme(Char) -> - case Char of - $" -> <<$\\, $">>; - $\\ -> <<$\\, $\\>>; - $\r -> <<$\\, $r>>; - $\n -> <<$\\, $n>>; - $\t -> <<$\\, $t>>; - $\f -> <<$\\, $f>>; - X when X > 126, X < 160 -> inspect@convert_to_u(X); - X when X < 32 -> inspect@convert_to_u(X); - Other -> <> - end. - -inspect@convert_to_u(Code) -> - erlang:list_to_binary(io_lib:format("\\u{~4.16.0B}", [Code])). - -inspect@proper_or_improper_list(List) -> - case List of - [] -> - {proper, []}; - [First] -> - {proper, [echo@inspect(First)]}; - [First | Rest] when erlang:is_list(Rest) -> - {Kind, Inspected} = inspect@proper_or_improper_list(Rest), - {Kind, [echo@inspect(First), ", " | Inspected]}; - [First | ImproperRest] -> - {improper, [echo@inspect(First), " | ", echo@inspect(ImproperRest)]} - end. - -inspect@maybe_gleam_atom(Atom, PrevChar, Acc) -> - case {Atom, PrevChar} of - {<<>>, none} -> - {error, nil}; - {<>, none} when ?is_digit_char(First) -> - {error, nil}; - {<<"_", _/binary>>, none} -> - {error, nil}; - {<<"_">>, _} -> - {error, nil}; - {<<"_", _/binary>>, $_} -> - {error, nil}; - {<>, _} when not ?is_atom_char(First) -> - {error, nil}; - {<>, none} -> - inspect@maybe_gleam_atom(Rest, First, <>); - {<<"_", Rest/binary>>, _} -> - inspect@maybe_gleam_atom(Rest, $_, Acc); - {<>, $_} -> - inspect@maybe_gleam_atom(Rest, First, <>); - {<>, _} -> - inspect@maybe_gleam_atom(Rest, First, <>); - {<<>>, _} -> - {ok, Acc}; - _ -> - erlang:throw({gleam_error, echo, Atom, PrevChar, Acc}) - end. - -inspect@uppercase(X) -> X - 32. - diff --git a/test-output/cases/echo_nil/build/dev/erlang/echo_nil/ebin/echo_nil.app b/test-output/cases/echo_nil/build/dev/erlang/echo_nil/ebin/echo_nil.app deleted file mode 100644 index 4e08363a272..00000000000 --- a/test-output/cases/echo_nil/build/dev/erlang/echo_nil/ebin/echo_nil.app +++ /dev/null @@ -1,7 +0,0 @@ -{application, echo_nil, [ - {vsn, "1.0.0"}, - {applications, []}, - {description, ""}, - {modules, [main]}, - {registered, []} -]}. diff --git a/test-output/cases/echo_nil/build/dev/erlang/gleam_version b/test-output/cases/echo_nil/build/dev/erlang/gleam_version deleted file mode 100644 index 3e1ad720b13..00000000000 --- a/test-output/cases/echo_nil/build/dev/erlang/gleam_version +++ /dev/null @@ -1 +0,0 @@ -1.5.0 \ No newline at end of file diff --git a/test-output/cases/echo_nil/build/dev/javascript/echo_nil/_gleam_artefacts/main.cache b/test-output/cases/echo_nil/build/dev/javascript/echo_nil/_gleam_artefacts/main.cache deleted file mode 100644 index fa4c124a253..00000000000 Binary files a/test-output/cases/echo_nil/build/dev/javascript/echo_nil/_gleam_artefacts/main.cache and /dev/null differ diff --git a/test-output/cases/echo_nil/build/dev/javascript/echo_nil/_gleam_artefacts/main.cache_meta b/test-output/cases/echo_nil/build/dev/javascript/echo_nil/_gleam_artefacts/main.cache_meta deleted file mode 100644 index 78ea6ee58dc..00000000000 Binary files a/test-output/cases/echo_nil/build/dev/javascript/echo_nil/_gleam_artefacts/main.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_nil/build/dev/javascript/echo_nil/_gleam_artefacts/main.cache_warnings b/test-output/cases/echo_nil/build/dev/javascript/echo_nil/_gleam_artefacts/main.cache_warnings deleted file mode 100644 index 1b1cb4d44c5..00000000000 Binary files a/test-output/cases/echo_nil/build/dev/javascript/echo_nil/_gleam_artefacts/main.cache_warnings and /dev/null differ diff --git a/test-output/cases/echo_nil/build/dev/javascript/echo_nil/gleam.main.mjs b/test-output/cases/echo_nil/build/dev/javascript/echo_nil/gleam.main.mjs deleted file mode 100644 index e230911e646..00000000000 --- a/test-output/cases/echo_nil/build/dev/javascript/echo_nil/gleam.main.mjs +++ /dev/null @@ -1,2 +0,0 @@ -import { main } from "./main.mjs"; -main(); diff --git a/test-output/cases/echo_nil/build/dev/javascript/echo_nil/gleam.mjs b/test-output/cases/echo_nil/build/dev/javascript/echo_nil/gleam.mjs deleted file mode 100644 index 197cbbc35d4..00000000000 --- a/test-output/cases/echo_nil/build/dev/javascript/echo_nil/gleam.mjs +++ /dev/null @@ -1 +0,0 @@ -export * from "../prelude.mjs"; diff --git a/test-output/cases/echo_nil/build/dev/javascript/echo_nil/main.mjs b/test-output/cases/echo_nil/build/dev/javascript/echo_nil/main.mjs deleted file mode 100644 index 57b8eb0be2e..00000000000 --- a/test-output/cases/echo_nil/build/dev/javascript/echo_nil/main.mjs +++ /dev/null @@ -1,127 +0,0 @@ -import { - BitArray as $BitArray, - List as $List, - UtfCodepoint as $UtfCodepoint, - CustomType as $CustomType, -} from "./gleam.mjs"; - -export function main() { - return echo(undefined, "src/main.gleam", 2); -} - -function echo(value, file, line) { - const grey = "\u001b[90m"; - const reset_color = "\u001b[39m"; - const file_line = `${file}:${line}`; - const string_value = echo$inspect(value); - - if (typeof process === "object" && process.stderr?.write) { - // If we're in Node.js, use `stderr` - const string = `${grey}${file_line}${reset_color}\n${string_value}\n`; - process.stderr.write(string); - } else if (typeof Deno === "object") { - // If we're in Deno, use `stderr` - const string = `${grey}${file_line}${reset_color}\n${string_value}\n`; - Deno.stderr.writeSync(new TextEncoder().encode(string)); - } else { - // Otherwise, use `console.log` - // The browser's console.log doesn't support ansi escape codes - const string = `${file_line}\n${string_value}`; - console.log(string); - } - - return value; -} - -function echo$inspectString(str) { - let new_str = '"'; - for (let i = 0; i < str.length; i++) { - let char = str[i]; - if (char == "\n") new_str += "\\n"; - else if (char == "\r") new_str += "\\r"; - else if (char == "\t") new_str += "\\t"; - else if (char == "\f") new_str += "\\f"; - else if (char == "\\") new_str += "\\\\"; - else if (char == '"') new_str += '\\"'; - else if (char < " " || (char > "~" && char < "\u{00A0}")) { - new_str += "\\u{" + char.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0") + "}"; - } else { - new_str += char; - } - } - new_str += '"'; - return new_str; -} - -function echo$inspectDict(map) { - let body = "dict.from_list(["; - let first = true; - map.forEach((value, key) => { - if (!first) body = body + ", "; - body = body + "#(" + echo$inspect(key) + ", " + echo$inspect(value) + ")"; - first = false; - }); - return body + "])"; -} - -function echo$inspectCustomType(record) { - const props = Object.keys(record) - .map((label) => { - const value = echo$inspect(record[label]); - return isNaN(parseInt(label)) ? `${label}: ${value}` : value; - }) - .join(", "); - return props ? `${record.constructor.name}(${props})` : record.constructor.name; -} - -function echo$inspectObject(v) { - const name = Object.getPrototypeOf(v)?.constructor?.name || "Object"; - const props = []; - for (const k of Object.keys(v)) { - props.push(`${echo$inspect(k)}: ${echo$inspect(v[k])}`); - } - const body = props.length ? " " + props.join(", ") + " " : ""; - const head = name === "Object" ? "" : name + " "; - return `//js(${head}{${body}})`; -} - -function echo$inspect(v) { - const t = typeof v; - if (v === true) return "True"; - if (v === false) return "False"; - if (v === null) return "//js(null)"; - if (v === undefined) return "Nil"; - if (t === "string") return echo$inspectString(v); - if (t === "bigint" || t === "number") return v.toString(); - if (Array.isArray(v)) return `#(${v.map(echo$inspect).join(", ")})`; - if (v instanceof $List) return `[${v.toArray().map(echo$inspect).join(", ")}]`; - if (v instanceof $UtfCodepoint) return `//utfcodepoint(${String.fromCodePoint(v.value)})`; - if (v instanceof $BitArray) return `<<${Array.from(v.buffer).join(", ")}>>`; - if (v instanceof $CustomType) return echo$inspectCustomType(v); - if (echo$isDict(v)) return echo$inspectDict(v); - if (v instanceof Set) return `//js(Set(${[...v].map(echo$inspect).join(", ")}))`; - if (v instanceof RegExp) return `//js(${v})`; - if (v instanceof Date) return `//js(Date("${v.toISOString()}"))`; - if (v instanceof Function) { - const args = []; - for (const i of Array(v.length).keys()) args.push(String.fromCharCode(i + 97)); - return `//fn(${args.join(", ")}) { ... }`; - } - return echo$inspectObject(v); -} - -function echo$isDict(value) { - try { - // We can only check if an object is a stdlib Dict if it is one of the - // project's dependencies. - // The `Dict` class is the default export of `stdlib/dict.mjs` - // that we import as `$stdlib$dict`. - return value instanceof $stdlib$dict.default; - } catch { - // If stdlib is not one of the project's dependencies then `$stdlib$dict` - // will not have been imported and the check will throw an exception meaning - // we can't check if something is actually a `Dict`. - return false; - } -} - diff --git a/test-output/cases/echo_nil/build/dev/javascript/gleam_version b/test-output/cases/echo_nil/build/dev/javascript/gleam_version deleted file mode 100644 index 3e1ad720b13..00000000000 --- a/test-output/cases/echo_nil/build/dev/javascript/gleam_version +++ /dev/null @@ -1 +0,0 @@ -1.5.0 \ No newline at end of file diff --git a/test-output/cases/echo_nil/build/dev/javascript/prelude.mjs b/test-output/cases/echo_nil/build/dev/javascript/prelude.mjs deleted file mode 100644 index d2adeef273f..00000000000 --- a/test-output/cases/echo_nil/build/dev/javascript/prelude.mjs +++ /dev/null @@ -1,455 +0,0 @@ -// Values marked with @internal are not part of the public API and may change -// without notice. - -export class CustomType { - withFields(fields) { - let properties = Object.keys(this).map((label) => - label in fields ? fields[label] : this[label], - ); - return new this.constructor(...properties); - } -} - -export class List { - static fromArray(array, tail) { - let t = tail || new Empty(); - for (let i = array.length - 1; i >= 0; --i) { - t = new NonEmpty(array[i], t); - } - return t; - } - - [Symbol.iterator]() { - return new ListIterator(this); - } - - toArray() { - return [...this]; - } - - // @internal - atLeastLength(desired) { - for (let _ of this) { - if (desired <= 0) return true; - desired--; - } - return desired <= 0; - } - - // @internal - hasLength(desired) { - for (let _ of this) { - if (desired <= 0) return false; - desired--; - } - return desired === 0; - } - - // @internal - countLength() { - let length = 0; - for (let _ of this) length++; - return length; - } -} - -// @internal -export function prepend(element, tail) { - return new NonEmpty(element, tail); -} - -export function toList(elements, tail) { - return List.fromArray(elements, tail); -} - -// @internal -class ListIterator { - #current; - - constructor(current) { - this.#current = current; - } - - next() { - if (this.#current instanceof Empty) { - return { done: true }; - } else { - let { head, tail } = this.#current; - this.#current = tail; - return { value: head, done: false }; - } - } -} - -export class Empty extends List {} - -export class NonEmpty extends List { - constructor(head, tail) { - super(); - this.head = head; - this.tail = tail; - } -} - -export class BitArray { - constructor(buffer) { - if (!(buffer instanceof Uint8Array)) { - throw "BitArray can only be constructed from a Uint8Array"; - } - this.buffer = buffer; - } - - // @internal - get length() { - return this.buffer.length; - } - - // @internal - byteAt(index) { - return this.buffer[index]; - } - - // @internal - floatFromSlice(start, end, isBigEndian) { - return byteArrayToFloat(this.buffer, start, end, isBigEndian); - } - - // @internal - intFromSlice(start, end, isBigEndian, isSigned) { - return byteArrayToInt(this.buffer, start, end, isBigEndian, isSigned); - } - - // @internal - binaryFromSlice(start, end) { - return new BitArray(this.buffer.slice(start, end)); - } - - // @internal - sliceAfter(index) { - return new BitArray(this.buffer.slice(index)); - } -} - -export class UtfCodepoint { - constructor(value) { - this.value = value; - } -} - -// @internal -export function toBitArray(segments) { - if (segments.length === 0) { - return new BitArray(new Uint8Array()); - } - - if (segments.length === 1) { - // When there is a single Uint8Array segment, pass it directly to the bit - // array constructor to avoid a copy - if (segments[0] instanceof Uint8Array) { - return new BitArray(segments[0]); - } - - return new BitArray(new Uint8Array(segments)); - } - - // Count the total number of bytes, and check if there are any Uint8Array - // segments - let bytes = 0; - let hasUint8ArraySegment = false; - for (const segment of segments) { - if (segment instanceof Uint8Array) { - bytes += segment.byteLength; - hasUint8ArraySegment = true; - } else { - bytes++; - } - } - - // If there aren't any Uint8Array segments then pass the segments array - // directly to the Uint8Array constructor - if (!hasUint8ArraySegment) { - return new BitArray(new Uint8Array(segments)); - } - - // Copy the segments into a Uint8Array - let u8Array = new Uint8Array(bytes); - let cursor = 0; - for (let segment of segments) { - if (segment instanceof Uint8Array) { - u8Array.set(segment, cursor); - cursor += segment.byteLength; - } else { - u8Array[cursor] = segment; - cursor++; - } - } - - return new BitArray(u8Array); -} - -// @internal -// Derived from this answer https://stackoverflow.com/questions/8482309/converting-javascript-integer-to-byte-array-and-back -export function sizedInt(value, size, isBigEndian) { - if (size < 0) { - return new Uint8Array(); - } - if (size % 8 != 0) { - const msg = `Bit arrays must be byte aligned on JavaScript, got size of ${size} bits`; - throw new globalThis.Error(msg); - } - - const byteArray = new Uint8Array(size / 8); - - // Convert negative number to two's complement representation - if (value < 0) { - value = 2 ** size + value; - } - - if (isBigEndian) { - for (let i = byteArray.length - 1; i >= 0; i--) { - const byte = value % 256; - byteArray[i] = byte; - value = (value - byte) / 256; - } - } else { - for (let i = 0; i < byteArray.length; i++) { - const byte = value % 256; - byteArray[i] = byte; - value = (value - byte) / 256; - } - } - - return byteArray; -} - -// @internal -export function byteArrayToInt(byteArray, start, end, isBigEndian, isSigned) { - let value = 0; - - // Read bytes as an unsigned integer value - if (isBigEndian) { - for (let i = start; i < end; i++) { - value = value * 256 + byteArray[i]; - } - } else { - for (let i = end - 1; i >= start; i--) { - value = value * 256 + byteArray[i]; - } - } - - if (isSigned) { - const byteSize = end - start; - - const highBit = 2 ** (byteSize * 8 - 1); - - // If the high bit is set and this is a signed integer, reinterpret as - // two's complement - if (value >= highBit) { - value -= highBit * 2; - } - } - - return value; -} - -// @internal -export function byteArrayToFloat(byteArray, start, end, isBigEndian) { - const view = new DataView(byteArray.buffer); - - const byteSize = end - start; - - if (byteSize === 8) { - return view.getFloat64(start, !isBigEndian); - } else if (byteSize === 4) { - return view.getFloat32(start, !isBigEndian); - } else { - const msg = `Sized floats must be 32-bit or 64-bit on JavaScript, got size of ${byteSize * 8} bits`; - throw new globalThis.Error(msg); - } -} - -// @internal -export function stringBits(string) { - return new TextEncoder().encode(string); -} - -// @internal -export function codepointBits(codepoint) { - return stringBits(String.fromCodePoint(codepoint.value)); -} - -// @internal -export function sizedFloat(float, size, isBigEndian) { - if (size !== 32 && size !== 64) { - const msg = `Sized floats must be 32-bit or 64-bit on JavaScript, got size of ${size} bits`; - throw new globalThis.Error(msg); - } - - const byteArray = new Uint8Array(size / 8); - - const view = new DataView(byteArray.buffer); - - if (size == 64) { - view.setFloat64(0, float, !isBigEndian); - } else if (size === 32) { - view.setFloat32(0, float, !isBigEndian); - } - - return byteArray; -} - -export class Result extends CustomType { - // @internal - static isResult(data) { - return data instanceof Result; - } -} - -export class Ok extends Result { - constructor(value) { - super(); - this[0] = value; - } - - // @internal - isOk() { - return true; - } -} - -export class Error extends Result { - constructor(detail) { - super(); - this[0] = detail; - } - - // @internal - isOk() { - return false; - } -} - -export function isEqual(x, y) { - let values = [x, y]; - - while (values.length) { - let a = values.pop(); - let b = values.pop(); - if (a === b) continue; - - if (!isObject(a) || !isObject(b)) return false; - let unequal = - !structurallyCompatibleObjects(a, b) || - unequalDates(a, b) || - unequalBuffers(a, b) || - unequalArrays(a, b) || - unequalMaps(a, b) || - unequalSets(a, b) || - unequalRegExps(a, b); - if (unequal) return false; - - const proto = Object.getPrototypeOf(a); - if (proto !== null && typeof proto.equals === "function") { - try { - if (a.equals(b)) continue; - else return false; - } catch {} - } - - let [keys, get] = getters(a); - for (let k of keys(a)) { - values.push(get(a, k), get(b, k)); - } - } - - return true; -} - -function getters(object) { - if (object instanceof Map) { - return [(x) => x.keys(), (x, y) => x.get(y)]; - } else { - let extra = object instanceof globalThis.Error ? ["message"] : []; - return [(x) => [...extra, ...Object.keys(x)], (x, y) => x[y]]; - } -} - -function unequalDates(a, b) { - return a instanceof Date && (a > b || a < b); -} - -function unequalBuffers(a, b) { - return ( - a.buffer instanceof ArrayBuffer && - a.BYTES_PER_ELEMENT && - !(a.byteLength === b.byteLength && a.every((n, i) => n === b[i])) - ); -} - -function unequalArrays(a, b) { - return Array.isArray(a) && a.length !== b.length; -} - -function unequalMaps(a, b) { - return a instanceof Map && a.size !== b.size; -} - -function unequalSets(a, b) { - return ( - a instanceof Set && (a.size != b.size || [...a].some((e) => !b.has(e))) - ); -} - -function unequalRegExps(a, b) { - return a instanceof RegExp && (a.source !== b.source || a.flags !== b.flags); -} - -function isObject(a) { - return typeof a === "object" && a !== null; -} - -function structurallyCompatibleObjects(a, b) { - if (typeof a !== "object" && typeof b !== "object" && (!a || !b)) - return false; - - let nonstructural = [Promise, WeakSet, WeakMap, Function]; - if (nonstructural.some((c) => a instanceof c)) return false; - - return a.constructor === b.constructor; -} - -// @internal -export function remainderInt(a, b) { - if (b === 0) { - return 0; - } else { - return a % b; - } -} - -// @internal -export function divideInt(a, b) { - return Math.trunc(divideFloat(a, b)); -} - -// @internal -export function divideFloat(a, b) { - if (b === 0) { - return 0; - } else { - return a / b; - } -} - -// @internal -export function makeError(variant, module, line, fn, message, extra) { - let error = new globalThis.Error(message); - error.gleam_error = variant; - error.module = module; - error.line = line; - error.function = fn; - // TODO: Remove this with Gleam v2.0.0 - error.fn = fn; - for (let k in extra) error[k] = extra[k]; - return error; -} diff --git a/test-output/cases/echo_nil/build/packages/packages.toml b/test-output/cases/echo_nil/build/packages/packages.toml deleted file mode 100644 index e74c18552bb..00000000000 --- a/test-output/cases/echo_nil/build/packages/packages.toml +++ /dev/null @@ -1 +0,0 @@ -[packages] diff --git a/test-output/cases/echo_nil/manifest.toml b/test-output/cases/echo_nil/manifest.toml deleted file mode 100644 index c5d779a3f81..00000000000 --- a/test-output/cases/echo_nil/manifest.toml +++ /dev/null @@ -1,7 +0,0 @@ -# This file was generated by Gleam -# You typically do not need to edit this file - -packages = [ -] - -[requirements] diff --git a/test-output/cases/echo_string/build/dev/erlang/echo_string/_gleam_artefacts/echo_string@@main.erl b/test-output/cases/echo_string/build/dev/erlang/echo_string/_gleam_artefacts/echo_string@@main.erl deleted file mode 100644 index b41b3a2d22b..00000000000 --- a/test-output/cases/echo_string/build/dev/erlang/echo_string/_gleam_artefacts/echo_string@@main.erl +++ /dev/null @@ -1,99 +0,0 @@ --module('echo_string@@main'). --export([run/1]). - --define(red, "\e[31;1m"). --define(grey, "\e[90m"). --define(reset_color, "\e[39m"). --define(reset_all, "\e[0m"). - -run(Module) -> - io:setopts(standard_io, [binary, {encoding, utf8}]), - io:setopts(standard_error, [{encoding, utf8}]), - process_flag(trap_exit, true), - Pid = spawn_link(fun() -> run_module(Module) end), - receive - {'EXIT', Pid, {Reason, StackTrace}} -> - print_error(exit, Reason, StackTrace), - init:stop(1) - end. - -run_module(Module) -> - try - {ok, _} = application:ensure_all_started('echo_string'), - erlang:process_flag(trap_exit, false), - Module:main(), - erlang:halt(0) - catch - Class:Reason:StackTrace -> - print_error(Class, Reason, StackTrace), - init:stop(1) - end. - -print_error(Class, Error, Stacktrace) -> - Printed = [ - ?red, "runtime error", ?reset_color, ": ", error_class(Class, Error), ?reset_all, - "\n\n", - error_message(Error), - "\n\n", - error_details(Class, Error), - "stacktrace:\n", - [error_frame(Line) || Line <- refine_first(Error, Stacktrace)] - ], - io:format(standard_error, "~ts~n", [Printed]). - -refine_first(#{gleam_error := _, line := L}, [{M, F, A, [{file, Fi} | _]} | S]) -> - [{M, F, A, [{file, Fi}, {line, L}]} | S]; -refine_first(_, S) -> - S. - -error_class(_, #{gleam_error := panic}) -> "panic"; -error_class(_, #{gleam_error := todo}) -> "todo"; -error_class(_, #{gleam_error := let_assert}) -> "let assert"; -error_class(Class, _) -> ["Erlang ", atom_to_binary(Class)]. - -error_message(#{gleam_error := _, message := M}) -> - M; -error_message(undef) -> - <<"A function was called but it did not exist."/utf8 >>; -error_message({case_clause, _}) -> - <<"No pattern matched in an Erlang case expression."/utf8>>; -error_message({badmatch, _}) -> - <<"An Erlang assignment pattern did not match."/utf8>>; -error_message(function_clause) -> - <<"No Erlang function clause matched the arguments it was called with."/utf8>>; -error_message(_) -> - <<"An error occurred outside of Gleam."/utf8>>. - -error_details(_, #{gleam_error := let_assert, value := V}) -> - ["unmatched value:\n ", print_term(V), $\n, $\n]; -error_details(_, {case_clause, V}) -> - ["unmatched value:\n ", print_term(V), $\n, $\n]; -error_details(_, {badmatch, V}) -> - ["unmatched value:\n ", print_term(V), $\n, $\n]; -error_details(_, #{gleam_error := _}) -> - []; -error_details(error, function_clause) -> - []; -error_details(error, undef) -> - []; -error_details(C, E) -> - ["erlang:", atom_to_binary(C), $(, print_term(E), $), $\n, $\n]. - -print_term(T) -> - try - gleam@string:inspect(T) - catch - _:_ -> io_lib:format("~p", [T]) - end. - -error_frame({?MODULE, _, _, _}) -> []; -error_frame({erl_eval, _, _, _}) -> []; -error_frame({init, _, _, _}) -> []; -error_frame({M, F, _, O}) -> - M1 = string:replace(atom_to_binary(M), "@", "/", all), - [" ", M1, $., atom_to_binary(F), error_frame_end(O), $\n]. - -error_frame_end([{file, Fi}, {line, L} | _]) -> - [?grey, $\s, Fi, $:, integer_to_binary(L), ?reset_all]; -error_frame_end(_) -> - [?grey, " unknown source", ?reset_all]. \ No newline at end of file diff --git a/test-output/cases/echo_string/build/dev/erlang/echo_string/_gleam_artefacts/gleam@@compile.erl b/test-output/cases/echo_string/build/dev/erlang/echo_string/_gleam_artefacts/gleam@@compile.erl deleted file mode 100644 index 3e0a645b737..00000000000 --- a/test-output/cases/echo_string/build/dev/erlang/echo_string/_gleam_artefacts/gleam@@compile.erl +++ /dev/null @@ -1,163 +0,0 @@ -#!/usr/bin/env escript --mode(compile). - -% TODO: Don't concurrently print warnings and errors -% TODO: Some tests - -main(_) -> compile_package_loop(). - -compile_package_loop() -> - case file:read_line(standard_io) of - eof -> ok; - {ok, Line} -> - Chars = unicode:characters_to_list(Line), - {ok, Tokens, _} = erl_scan:string(Chars), - {ok, {Lib, Out, Modules}} = erl_parse:parse_term(Tokens), - case compile_package(Lib, Out, Modules) of - ok -> io:put_chars("gleam-compile-result-ok\n"); - err -> io:put_chars("gleam-compile-result-error\n") - end, - compile_package_loop() - end. - -compile_package(Lib, Out, Modules) -> - IsElixirModule = fun(Module) -> - filename:extension(Module) =:= ".ex" - end, - {ElixirModules, ErlangModules} = lists:partition(IsElixirModule, Modules), - ok = configure_logging(), - ok = add_lib_to_erlang_path(Lib), - ok = filelib:ensure_dir([Out, $/]), - {ErlangOk, _ErlangBeams} = compile_erlang(ErlangModules, Out), - {ElixirOk, _ElixirBeams} = case ErlangOk of - true -> compile_elixir(ElixirModules, Out); - false -> {false, []} - end, - ok = del_lib_from_erlang_path(Lib), - case ErlangOk and ElixirOk of - true -> ok; - false -> err - end. - -compile_erlang(Modules, Out) -> - Workers = start_compiler_workers(Out), - ok = producer_loop(Modules, Workers), - collect_results({true, []}). - -collect_results(Acc = {Result, Beams}) -> - receive - {compiled, Beam} -> collect_results({Result, [Beam | Beams]}); - failed -> collect_results({false, Beams}) - after 0 -> Acc - end. - -producer_loop([], 0) -> - ok; -producer_loop([], Workers) -> - receive - {work_please, _} -> producer_loop([], Workers - 1) - end; -producer_loop([Module | Modules], Workers) -> - receive - {work_please, Worker} -> - erlang:send(Worker, {module, Module}), - producer_loop(Modules, Workers) - end. - -start_compiler_workers(Out) -> - Parent = self(), - NumSchedulers = erlang:system_info(schedulers), - SpawnWorker = fun(_) -> - erlang:spawn_link(fun() -> worker_loop(Parent, Out) end) - end, - lists:foreach(SpawnWorker, lists:seq(1, NumSchedulers)), - NumSchedulers. - -worker_loop(Parent, Out) -> - Options = [report_errors, report_warnings, debug_info, {outdir, Out}], - erlang:send(Parent, {work_please, self()}), - receive - {module, Module} -> - log({compiling, Module}), - case compile:file(Module, Options) of - {ok, ModuleName} -> - Beam = filename:join(Out, ModuleName) ++ ".beam", - Message = {compiled, Beam}, - log(Message), - erlang:send(Parent, Message); - error -> - log({failed, Module}), - erlang:send(Parent, failed) - end, - worker_loop(Parent, Out) - end. - -compile_elixir(Modules, Out) -> - Error = [ - "The program elixir was not found. Is it installed?", - $\n, - "Documentation for installing Elixir can be viewed here:", - $\n, - "https://elixir-lang.org/install.html" - ], - case Modules of - [] -> {true, []}; - _ -> - log({starting, "compiler.app"}), - ok = application:start(compiler), - log({starting, "elixir.app"}), - case application:start(elixir) of - ok -> do_compile_elixir(Modules, Out); - _ -> - io:put_chars(standard_error, [Error, $\n]), - {false, []} - end - end. - -do_compile_elixir(Modules, Out) -> - ModuleBins = lists:map(fun(Module) -> - log({compiling, Module}), - list_to_binary(Module) - end, Modules), - OutBin = list_to_binary(Out), - Options = [{dest, OutBin}], - % Silence "redefining module" warnings. - % Compiled modules in the build directory are added to the code path. - % These warnings result from recompiling loaded modules. - % TODO: This line can likely be removed if/when the build directory is cleaned before every compilation. - 'Elixir.Code':compiler_options([{ignore_module_conflict, true}]), - case 'Elixir.Kernel.ParallelCompiler':compile_to_path(ModuleBins, OutBin, Options) of - {ok, ModuleAtoms, _} -> - ToBeam = fun(ModuleAtom) -> - Beam = filename:join(Out, atom_to_list(ModuleAtom)) ++ ".beam", - log({compiled, Beam}), - Beam - end, - {true, lists:map(ToBeam, ModuleAtoms)}; - {error, Errors, _} -> - % Log all filenames associated with modules that failed to compile. - % Note: The compiler prints compilation errors upon encountering them. - ErrorFiles = lists:usort([File || {File, _, _} <- Errors]), - Log = fun(File) -> - log({failed, binary_to_list(File)}) - end, - lists:foreach(Log, ErrorFiles), - {false, []}; - _ -> {false, []} - end. - -add_lib_to_erlang_path(Lib) -> - code:add_paths(filelib:wildcard([Lib, "/*/ebin"])). - -del_lib_from_erlang_path(Lib) -> - code:del_paths(filelib:wildcard([Lib, "/*/ebin"])). - -configure_logging() -> - Enabled = os:getenv("GLEAM_LOG") /= false, - persistent_term:put(gleam_logging_enabled, Enabled). - -log(Term) -> - case persistent_term:get(gleam_logging_enabled) of - true -> erlang:display(Term), ok; - false -> ok - end. diff --git a/test-output/cases/echo_string/build/dev/erlang/echo_string/_gleam_artefacts/main.cache b/test-output/cases/echo_string/build/dev/erlang/echo_string/_gleam_artefacts/main.cache deleted file mode 100644 index 95e76778180..00000000000 Binary files a/test-output/cases/echo_string/build/dev/erlang/echo_string/_gleam_artefacts/main.cache and /dev/null differ diff --git a/test-output/cases/echo_string/build/dev/erlang/echo_string/_gleam_artefacts/main.cache_meta b/test-output/cases/echo_string/build/dev/erlang/echo_string/_gleam_artefacts/main.cache_meta deleted file mode 100644 index 32839ee3c7a..00000000000 Binary files a/test-output/cases/echo_string/build/dev/erlang/echo_string/_gleam_artefacts/main.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_string/build/dev/erlang/echo_string/_gleam_artefacts/main.cache_warnings b/test-output/cases/echo_string/build/dev/erlang/echo_string/_gleam_artefacts/main.cache_warnings deleted file mode 100644 index 1b1cb4d44c5..00000000000 Binary files a/test-output/cases/echo_string/build/dev/erlang/echo_string/_gleam_artefacts/main.cache_warnings and /dev/null differ diff --git a/test-output/cases/echo_string/build/dev/erlang/echo_string/_gleam_artefacts/main.erl b/test-output/cases/echo_string/build/dev/erlang/echo_string/_gleam_artefacts/main.erl deleted file mode 100644 index 2a891b16097..00000000000 --- a/test-output/cases/echo_string/build/dev/erlang/echo_string/_gleam_artefacts/main.erl +++ /dev/null @@ -1,192 +0,0 @@ --module(main). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([main/0]). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_string/src/main.gleam", 1). --spec main() -> binary(). -main() -> - echo(<<"hello world"/utf8>>, "src/main.gleam", 2), - echo(<<"multiline -string"/utf8>>, "src/main.gleam", 3), - echo(<<"string with\t\r\nescaped chars"/utf8>>, "src/main.gleam", 5). - --define(is_lowercase_char(X), (X > 96 andalso X < 123)). --define(is_underscore_char(X), (X == 95)). --define(is_digit_char(X), (X > 47 andalso X < 58)). --define(could_be_record(Tuple), - erlang:is_tuple(Tuple) andalso - erlang:is_atom(erlang:element(1, Tuple)) andalso - erlang:element(1, Tuple) =/= false andalso - erlang:element(1, Tuple) =/= true andalso - erlang:element(1, Tuple) =/= nil -). --define(is_atom_char(C), - (?is_lowercase_char(C) orelse - ?is_underscore_char(C) orelse - ?is_digit_char(C)) -). - --define(grey, "\e[90m"). --define(reset_color, "\e[39m"). - -echo(Value, File, Line) -> - StringLine = erlang:integer_to_list(Line), - StringValue = echo@inspect(Value), - io:put_chars( - standard_error, - [?grey, File, $:, StringLine, ?reset_color, $\n, StringValue, $\n] - ), - Value. - -echo@inspect(Value) -> - case Value of - nil -> "Nil"; - true -> "True"; - false -> "False"; - Int when erlang:is_integer(Int) -> erlang:integer_to_list(Int); - Float when erlang:is_float(Float) -> io_lib_format:fwrite_g(Float); - Binary when erlang:is_binary(Binary) -> inspect@binary(Binary); - Bits when erlang:is_bitstring(Bits) -> inspect@bit_array(Bits); - Atom when erlang:is_atom(Atom) -> inspect@atom(Atom); - List when erlang:is_list(List) -> inspect@list(List); - Map when erlang:is_map(Map) -> inspect@map(Map); - Record when ?could_be_record(Record) -> inspect@record(Record); - Tuple when erlang:is_tuple(Tuple) -> inspect@tuple(Tuple); - Function when erlang:is_function(Function) -> inspect@function(Function); - Any -> ["//erl(", io_lib:format("~p", [Any]), ")"] - end. - -inspect@bit_array(Bits) -> - Pieces = inspect@bit_array_pieces(Bits, []), - Inner = lists:join(", ", lists:reverse(Pieces)), - ["<<", Inner, ">>"]. - -inspect@bit_array_pieces(Bits, Acc) -> - case Bits of - <<>> -> - Acc; - <> -> - inspect@bit_array_pieces(Rest, [erlang:integer_to_binary(Byte) | Acc]); - _ -> - Size = erlang:bit_size(Bits), - <> = Bits, - SizeString = [":size(", erlang:integer_to_binary(Size), ")"], - Piece = [erlang:integer_to_binary(RemainingBits), SizeString], - [Piece | Acc] - end. - -inspect@binary(Binary) -> - case inspect@maybe_utf8_string(Binary, <<>>) of - {ok, InspectedUtf8String} -> - InspectedUtf8String; - {error, not_a_utf8_string} -> - Segments = [erlang:integer_to_list(X) || <> <= Binary], - ["<<", lists:join(", ", Segments), ">>"] - end. - -inspect@atom(Atom) -> - Binary = erlang:atom_to_binary(Atom), - case inspect@maybe_gleam_atom(Binary, none, <<>>) of - {ok, Inspected} -> Inspected; - {error, _} -> ["atom.create_from_string(\"", Binary, "\")"] - end. - -inspect@list(List) -> - case inspect@proper_or_improper_list(List) of - {proper, Elements} -> ["[", Elements, "]"]; - {improper, Elements} -> ["//erl([", Elements, "])"] - end. - -inspect@map(Map) -> - Fields = [ - [<<"#(">>, echo@inspect(Key), <<", ">>, echo@inspect(Value), <<")">>] - || {Key, Value} <- maps:to_list(Map) - ], - ["dict.from_list([", lists:join(", ", Fields), "])"]. - -inspect@record(Record) -> - [Atom | ArgsList] = erlang:tuple_to_list(Record), - Args = lists:join(", ", lists:map(fun echo@inspect/1, ArgsList)), - [echo@inspect(Atom), "(", Args, ")"]. - -inspect@tuple(Tuple) -> - Elements = lists:map(fun echo@inspect/1, erlang:tuple_to_list(Tuple)), - ["#(", lists:join(", ", Elements), ")"]. - -inspect@function(Function) -> - {arity, Arity} = erlang:fun_info(Function, arity), - ArgsAsciiCodes = lists:seq($a, $a + Arity - 1), - Args = lists:join(", ", lists:map(fun(Arg) -> <> end, ArgsAsciiCodes)), - ["//fn(", Args, ") { ... }"]. - -inspect@maybe_utf8_string(Binary, Acc) -> - case Binary of - <<>> -> - {ok, <<$", Acc/binary, $">>}; - <> -> - Escaped = inspect@escape_grapheme(First), - inspect@maybe_utf8_string(Rest, <>); - _ -> - {error, not_a_utf8_string} - end. - -inspect@escape_grapheme(Char) -> - case Char of - $" -> <<$\\, $">>; - $\\ -> <<$\\, $\\>>; - $\r -> <<$\\, $r>>; - $\n -> <<$\\, $n>>; - $\t -> <<$\\, $t>>; - $\f -> <<$\\, $f>>; - X when X > 126, X < 160 -> inspect@convert_to_u(X); - X when X < 32 -> inspect@convert_to_u(X); - Other -> <> - end. - -inspect@convert_to_u(Code) -> - erlang:list_to_binary(io_lib:format("\\u{~4.16.0B}", [Code])). - -inspect@proper_or_improper_list(List) -> - case List of - [] -> - {proper, []}; - [First] -> - {proper, [echo@inspect(First)]}; - [First | Rest] when erlang:is_list(Rest) -> - {Kind, Inspected} = inspect@proper_or_improper_list(Rest), - {Kind, [echo@inspect(First), ", " | Inspected]}; - [First | ImproperRest] -> - {improper, [echo@inspect(First), " | ", echo@inspect(ImproperRest)]} - end. - -inspect@maybe_gleam_atom(Atom, PrevChar, Acc) -> - case {Atom, PrevChar} of - {<<>>, none} -> - {error, nil}; - {<>, none} when ?is_digit_char(First) -> - {error, nil}; - {<<"_", _/binary>>, none} -> - {error, nil}; - {<<"_">>, _} -> - {error, nil}; - {<<"_", _/binary>>, $_} -> - {error, nil}; - {<>, _} when not ?is_atom_char(First) -> - {error, nil}; - {<>, none} -> - inspect@maybe_gleam_atom(Rest, First, <>); - {<<"_", Rest/binary>>, _} -> - inspect@maybe_gleam_atom(Rest, $_, Acc); - {<>, $_} -> - inspect@maybe_gleam_atom(Rest, First, <>); - {<>, _} -> - inspect@maybe_gleam_atom(Rest, First, <>); - {<<>>, _} -> - {ok, Acc}; - _ -> - erlang:throw({gleam_error, echo, Atom, PrevChar, Acc}) - end. - -inspect@uppercase(X) -> X - 32. - diff --git a/test-output/cases/echo_string/build/dev/erlang/echo_string/ebin/echo_string.app b/test-output/cases/echo_string/build/dev/erlang/echo_string/ebin/echo_string.app deleted file mode 100644 index 373bf9c63a1..00000000000 --- a/test-output/cases/echo_string/build/dev/erlang/echo_string/ebin/echo_string.app +++ /dev/null @@ -1,7 +0,0 @@ -{application, echo_string, [ - {vsn, "1.0.0"}, - {applications, []}, - {description, ""}, - {modules, [main]}, - {registered, []} -]}. diff --git a/test-output/cases/echo_string/build/dev/erlang/gleam_version b/test-output/cases/echo_string/build/dev/erlang/gleam_version deleted file mode 100644 index 3e1ad720b13..00000000000 --- a/test-output/cases/echo_string/build/dev/erlang/gleam_version +++ /dev/null @@ -1 +0,0 @@ -1.5.0 \ No newline at end of file diff --git a/test-output/cases/echo_string/build/dev/javascript/echo_string/_gleam_artefacts/main.cache b/test-output/cases/echo_string/build/dev/javascript/echo_string/_gleam_artefacts/main.cache deleted file mode 100644 index 672d74b1522..00000000000 Binary files a/test-output/cases/echo_string/build/dev/javascript/echo_string/_gleam_artefacts/main.cache and /dev/null differ diff --git a/test-output/cases/echo_string/build/dev/javascript/echo_string/_gleam_artefacts/main.cache_meta b/test-output/cases/echo_string/build/dev/javascript/echo_string/_gleam_artefacts/main.cache_meta deleted file mode 100644 index 32839ee3c7a..00000000000 Binary files a/test-output/cases/echo_string/build/dev/javascript/echo_string/_gleam_artefacts/main.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_string/build/dev/javascript/echo_string/_gleam_artefacts/main.cache_warnings b/test-output/cases/echo_string/build/dev/javascript/echo_string/_gleam_artefacts/main.cache_warnings deleted file mode 100644 index 1b1cb4d44c5..00000000000 Binary files a/test-output/cases/echo_string/build/dev/javascript/echo_string/_gleam_artefacts/main.cache_warnings and /dev/null differ diff --git a/test-output/cases/echo_string/build/dev/javascript/echo_string/gleam.main.mjs b/test-output/cases/echo_string/build/dev/javascript/echo_string/gleam.main.mjs deleted file mode 100644 index e230911e646..00000000000 --- a/test-output/cases/echo_string/build/dev/javascript/echo_string/gleam.main.mjs +++ /dev/null @@ -1,2 +0,0 @@ -import { main } from "./main.mjs"; -main(); diff --git a/test-output/cases/echo_string/build/dev/javascript/echo_string/gleam.mjs b/test-output/cases/echo_string/build/dev/javascript/echo_string/gleam.mjs deleted file mode 100644 index 197cbbc35d4..00000000000 --- a/test-output/cases/echo_string/build/dev/javascript/echo_string/gleam.mjs +++ /dev/null @@ -1 +0,0 @@ -export * from "../prelude.mjs"; diff --git a/test-output/cases/echo_string/build/dev/javascript/echo_string/main.mjs b/test-output/cases/echo_string/build/dev/javascript/echo_string/main.mjs deleted file mode 100644 index e6651a325a3..00000000000 --- a/test-output/cases/echo_string/build/dev/javascript/echo_string/main.mjs +++ /dev/null @@ -1,129 +0,0 @@ -import { - BitArray as $BitArray, - List as $List, - UtfCodepoint as $UtfCodepoint, - CustomType as $CustomType, -} from "./gleam.mjs"; - -export function main() { - echo("hello world", "src/main.gleam", 2); - echo("multiline\nstring", "src/main.gleam", 3); - return echo("string with\t\r\nescaped chars", "src/main.gleam", 5); -} - -function echo(value, file, line) { - const grey = "\u001b[90m"; - const reset_color = "\u001b[39m"; - const file_line = `${file}:${line}`; - const string_value = echo$inspect(value); - - if (typeof process === "object" && process.stderr?.write) { - // If we're in Node.js, use `stderr` - const string = `${grey}${file_line}${reset_color}\n${string_value}\n`; - process.stderr.write(string); - } else if (typeof Deno === "object") { - // If we're in Deno, use `stderr` - const string = `${grey}${file_line}${reset_color}\n${string_value}\n`; - Deno.stderr.writeSync(new TextEncoder().encode(string)); - } else { - // Otherwise, use `console.log` - // The browser's console.log doesn't support ansi escape codes - const string = `${file_line}\n${string_value}`; - console.log(string); - } - - return value; -} - -function echo$inspectString(str) { - let new_str = '"'; - for (let i = 0; i < str.length; i++) { - let char = str[i]; - if (char == "\n") new_str += "\\n"; - else if (char == "\r") new_str += "\\r"; - else if (char == "\t") new_str += "\\t"; - else if (char == "\f") new_str += "\\f"; - else if (char == "\\") new_str += "\\\\"; - else if (char == '"') new_str += '\\"'; - else if (char < " " || (char > "~" && char < "\u{00A0}")) { - new_str += "\\u{" + char.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0") + "}"; - } else { - new_str += char; - } - } - new_str += '"'; - return new_str; -} - -function echo$inspectDict(map) { - let body = "dict.from_list(["; - let first = true; - map.forEach((value, key) => { - if (!first) body = body + ", "; - body = body + "#(" + echo$inspect(key) + ", " + echo$inspect(value) + ")"; - first = false; - }); - return body + "])"; -} - -function echo$inspectCustomType(record) { - const props = Object.keys(record) - .map((label) => { - const value = echo$inspect(record[label]); - return isNaN(parseInt(label)) ? `${label}: ${value}` : value; - }) - .join(", "); - return props ? `${record.constructor.name}(${props})` : record.constructor.name; -} - -function echo$inspectObject(v) { - const name = Object.getPrototypeOf(v)?.constructor?.name || "Object"; - const props = []; - for (const k of Object.keys(v)) { - props.push(`${echo$inspect(k)}: ${echo$inspect(v[k])}`); - } - const body = props.length ? " " + props.join(", ") + " " : ""; - const head = name === "Object" ? "" : name + " "; - return `//js(${head}{${body}})`; -} - -function echo$inspect(v) { - const t = typeof v; - if (v === true) return "True"; - if (v === false) return "False"; - if (v === null) return "//js(null)"; - if (v === undefined) return "Nil"; - if (t === "string") return echo$inspectString(v); - if (t === "bigint" || t === "number") return v.toString(); - if (Array.isArray(v)) return `#(${v.map(echo$inspect).join(", ")})`; - if (v instanceof $List) return `[${v.toArray().map(echo$inspect).join(", ")}]`; - if (v instanceof $UtfCodepoint) return `//utfcodepoint(${String.fromCodePoint(v.value)})`; - if (v instanceof $BitArray) return `<<${Array.from(v.buffer).join(", ")}>>`; - if (v instanceof $CustomType) return echo$inspectCustomType(v); - if (echo$isDict(v)) return echo$inspectDict(v); - if (v instanceof Set) return `//js(Set(${[...v].map(echo$inspect).join(", ")}))`; - if (v instanceof RegExp) return `//js(${v})`; - if (v instanceof Date) return `//js(Date("${v.toISOString()}"))`; - if (v instanceof Function) { - const args = []; - for (const i of Array(v.length).keys()) args.push(String.fromCharCode(i + 97)); - return `//fn(${args.join(", ")}) { ... }`; - } - return echo$inspectObject(v); -} - -function echo$isDict(value) { - try { - // We can only check if an object is a stdlib Dict if it is one of the - // project's dependencies. - // The `Dict` class is the default export of `stdlib/dict.mjs` - // that we import as `$stdlib$dict`. - return value instanceof $stdlib$dict.default; - } catch { - // If stdlib is not one of the project's dependencies then `$stdlib$dict` - // will not have been imported and the check will throw an exception meaning - // we can't check if something is actually a `Dict`. - return false; - } -} - diff --git a/test-output/cases/echo_string/build/dev/javascript/gleam_version b/test-output/cases/echo_string/build/dev/javascript/gleam_version deleted file mode 100644 index 3e1ad720b13..00000000000 --- a/test-output/cases/echo_string/build/dev/javascript/gleam_version +++ /dev/null @@ -1 +0,0 @@ -1.5.0 \ No newline at end of file diff --git a/test-output/cases/echo_string/build/dev/javascript/prelude.mjs b/test-output/cases/echo_string/build/dev/javascript/prelude.mjs deleted file mode 100644 index d2adeef273f..00000000000 --- a/test-output/cases/echo_string/build/dev/javascript/prelude.mjs +++ /dev/null @@ -1,455 +0,0 @@ -// Values marked with @internal are not part of the public API and may change -// without notice. - -export class CustomType { - withFields(fields) { - let properties = Object.keys(this).map((label) => - label in fields ? fields[label] : this[label], - ); - return new this.constructor(...properties); - } -} - -export class List { - static fromArray(array, tail) { - let t = tail || new Empty(); - for (let i = array.length - 1; i >= 0; --i) { - t = new NonEmpty(array[i], t); - } - return t; - } - - [Symbol.iterator]() { - return new ListIterator(this); - } - - toArray() { - return [...this]; - } - - // @internal - atLeastLength(desired) { - for (let _ of this) { - if (desired <= 0) return true; - desired--; - } - return desired <= 0; - } - - // @internal - hasLength(desired) { - for (let _ of this) { - if (desired <= 0) return false; - desired--; - } - return desired === 0; - } - - // @internal - countLength() { - let length = 0; - for (let _ of this) length++; - return length; - } -} - -// @internal -export function prepend(element, tail) { - return new NonEmpty(element, tail); -} - -export function toList(elements, tail) { - return List.fromArray(elements, tail); -} - -// @internal -class ListIterator { - #current; - - constructor(current) { - this.#current = current; - } - - next() { - if (this.#current instanceof Empty) { - return { done: true }; - } else { - let { head, tail } = this.#current; - this.#current = tail; - return { value: head, done: false }; - } - } -} - -export class Empty extends List {} - -export class NonEmpty extends List { - constructor(head, tail) { - super(); - this.head = head; - this.tail = tail; - } -} - -export class BitArray { - constructor(buffer) { - if (!(buffer instanceof Uint8Array)) { - throw "BitArray can only be constructed from a Uint8Array"; - } - this.buffer = buffer; - } - - // @internal - get length() { - return this.buffer.length; - } - - // @internal - byteAt(index) { - return this.buffer[index]; - } - - // @internal - floatFromSlice(start, end, isBigEndian) { - return byteArrayToFloat(this.buffer, start, end, isBigEndian); - } - - // @internal - intFromSlice(start, end, isBigEndian, isSigned) { - return byteArrayToInt(this.buffer, start, end, isBigEndian, isSigned); - } - - // @internal - binaryFromSlice(start, end) { - return new BitArray(this.buffer.slice(start, end)); - } - - // @internal - sliceAfter(index) { - return new BitArray(this.buffer.slice(index)); - } -} - -export class UtfCodepoint { - constructor(value) { - this.value = value; - } -} - -// @internal -export function toBitArray(segments) { - if (segments.length === 0) { - return new BitArray(new Uint8Array()); - } - - if (segments.length === 1) { - // When there is a single Uint8Array segment, pass it directly to the bit - // array constructor to avoid a copy - if (segments[0] instanceof Uint8Array) { - return new BitArray(segments[0]); - } - - return new BitArray(new Uint8Array(segments)); - } - - // Count the total number of bytes, and check if there are any Uint8Array - // segments - let bytes = 0; - let hasUint8ArraySegment = false; - for (const segment of segments) { - if (segment instanceof Uint8Array) { - bytes += segment.byteLength; - hasUint8ArraySegment = true; - } else { - bytes++; - } - } - - // If there aren't any Uint8Array segments then pass the segments array - // directly to the Uint8Array constructor - if (!hasUint8ArraySegment) { - return new BitArray(new Uint8Array(segments)); - } - - // Copy the segments into a Uint8Array - let u8Array = new Uint8Array(bytes); - let cursor = 0; - for (let segment of segments) { - if (segment instanceof Uint8Array) { - u8Array.set(segment, cursor); - cursor += segment.byteLength; - } else { - u8Array[cursor] = segment; - cursor++; - } - } - - return new BitArray(u8Array); -} - -// @internal -// Derived from this answer https://stackoverflow.com/questions/8482309/converting-javascript-integer-to-byte-array-and-back -export function sizedInt(value, size, isBigEndian) { - if (size < 0) { - return new Uint8Array(); - } - if (size % 8 != 0) { - const msg = `Bit arrays must be byte aligned on JavaScript, got size of ${size} bits`; - throw new globalThis.Error(msg); - } - - const byteArray = new Uint8Array(size / 8); - - // Convert negative number to two's complement representation - if (value < 0) { - value = 2 ** size + value; - } - - if (isBigEndian) { - for (let i = byteArray.length - 1; i >= 0; i--) { - const byte = value % 256; - byteArray[i] = byte; - value = (value - byte) / 256; - } - } else { - for (let i = 0; i < byteArray.length; i++) { - const byte = value % 256; - byteArray[i] = byte; - value = (value - byte) / 256; - } - } - - return byteArray; -} - -// @internal -export function byteArrayToInt(byteArray, start, end, isBigEndian, isSigned) { - let value = 0; - - // Read bytes as an unsigned integer value - if (isBigEndian) { - for (let i = start; i < end; i++) { - value = value * 256 + byteArray[i]; - } - } else { - for (let i = end - 1; i >= start; i--) { - value = value * 256 + byteArray[i]; - } - } - - if (isSigned) { - const byteSize = end - start; - - const highBit = 2 ** (byteSize * 8 - 1); - - // If the high bit is set and this is a signed integer, reinterpret as - // two's complement - if (value >= highBit) { - value -= highBit * 2; - } - } - - return value; -} - -// @internal -export function byteArrayToFloat(byteArray, start, end, isBigEndian) { - const view = new DataView(byteArray.buffer); - - const byteSize = end - start; - - if (byteSize === 8) { - return view.getFloat64(start, !isBigEndian); - } else if (byteSize === 4) { - return view.getFloat32(start, !isBigEndian); - } else { - const msg = `Sized floats must be 32-bit or 64-bit on JavaScript, got size of ${byteSize * 8} bits`; - throw new globalThis.Error(msg); - } -} - -// @internal -export function stringBits(string) { - return new TextEncoder().encode(string); -} - -// @internal -export function codepointBits(codepoint) { - return stringBits(String.fromCodePoint(codepoint.value)); -} - -// @internal -export function sizedFloat(float, size, isBigEndian) { - if (size !== 32 && size !== 64) { - const msg = `Sized floats must be 32-bit or 64-bit on JavaScript, got size of ${size} bits`; - throw new globalThis.Error(msg); - } - - const byteArray = new Uint8Array(size / 8); - - const view = new DataView(byteArray.buffer); - - if (size == 64) { - view.setFloat64(0, float, !isBigEndian); - } else if (size === 32) { - view.setFloat32(0, float, !isBigEndian); - } - - return byteArray; -} - -export class Result extends CustomType { - // @internal - static isResult(data) { - return data instanceof Result; - } -} - -export class Ok extends Result { - constructor(value) { - super(); - this[0] = value; - } - - // @internal - isOk() { - return true; - } -} - -export class Error extends Result { - constructor(detail) { - super(); - this[0] = detail; - } - - // @internal - isOk() { - return false; - } -} - -export function isEqual(x, y) { - let values = [x, y]; - - while (values.length) { - let a = values.pop(); - let b = values.pop(); - if (a === b) continue; - - if (!isObject(a) || !isObject(b)) return false; - let unequal = - !structurallyCompatibleObjects(a, b) || - unequalDates(a, b) || - unequalBuffers(a, b) || - unequalArrays(a, b) || - unequalMaps(a, b) || - unequalSets(a, b) || - unequalRegExps(a, b); - if (unequal) return false; - - const proto = Object.getPrototypeOf(a); - if (proto !== null && typeof proto.equals === "function") { - try { - if (a.equals(b)) continue; - else return false; - } catch {} - } - - let [keys, get] = getters(a); - for (let k of keys(a)) { - values.push(get(a, k), get(b, k)); - } - } - - return true; -} - -function getters(object) { - if (object instanceof Map) { - return [(x) => x.keys(), (x, y) => x.get(y)]; - } else { - let extra = object instanceof globalThis.Error ? ["message"] : []; - return [(x) => [...extra, ...Object.keys(x)], (x, y) => x[y]]; - } -} - -function unequalDates(a, b) { - return a instanceof Date && (a > b || a < b); -} - -function unequalBuffers(a, b) { - return ( - a.buffer instanceof ArrayBuffer && - a.BYTES_PER_ELEMENT && - !(a.byteLength === b.byteLength && a.every((n, i) => n === b[i])) - ); -} - -function unequalArrays(a, b) { - return Array.isArray(a) && a.length !== b.length; -} - -function unequalMaps(a, b) { - return a instanceof Map && a.size !== b.size; -} - -function unequalSets(a, b) { - return ( - a instanceof Set && (a.size != b.size || [...a].some((e) => !b.has(e))) - ); -} - -function unequalRegExps(a, b) { - return a instanceof RegExp && (a.source !== b.source || a.flags !== b.flags); -} - -function isObject(a) { - return typeof a === "object" && a !== null; -} - -function structurallyCompatibleObjects(a, b) { - if (typeof a !== "object" && typeof b !== "object" && (!a || !b)) - return false; - - let nonstructural = [Promise, WeakSet, WeakMap, Function]; - if (nonstructural.some((c) => a instanceof c)) return false; - - return a.constructor === b.constructor; -} - -// @internal -export function remainderInt(a, b) { - if (b === 0) { - return 0; - } else { - return a % b; - } -} - -// @internal -export function divideInt(a, b) { - return Math.trunc(divideFloat(a, b)); -} - -// @internal -export function divideFloat(a, b) { - if (b === 0) { - return 0; - } else { - return a / b; - } -} - -// @internal -export function makeError(variant, module, line, fn, message, extra) { - let error = new globalThis.Error(message); - error.gleam_error = variant; - error.module = module; - error.line = line; - error.function = fn; - // TODO: Remove this with Gleam v2.0.0 - error.fn = fn; - for (let k in extra) error[k] = extra[k]; - return error; -} diff --git a/test-output/cases/echo_string/build/packages/packages.toml b/test-output/cases/echo_string/build/packages/packages.toml deleted file mode 100644 index e74c18552bb..00000000000 --- a/test-output/cases/echo_string/build/packages/packages.toml +++ /dev/null @@ -1 +0,0 @@ -[packages] diff --git a/test-output/cases/echo_string/manifest.toml b/test-output/cases/echo_string/manifest.toml deleted file mode 100644 index c5d779a3f81..00000000000 --- a/test-output/cases/echo_string/manifest.toml +++ /dev/null @@ -1,7 +0,0 @@ -# This file was generated by Gleam -# You typically do not need to edit this file - -packages = [ -] - -[requirements] diff --git a/test-output/cases/echo_tuple/build/dev/erlang/echo_tuple/_gleam_artefacts/echo_tuple@@main.erl b/test-output/cases/echo_tuple/build/dev/erlang/echo_tuple/_gleam_artefacts/echo_tuple@@main.erl deleted file mode 100644 index 8dcada176f1..00000000000 --- a/test-output/cases/echo_tuple/build/dev/erlang/echo_tuple/_gleam_artefacts/echo_tuple@@main.erl +++ /dev/null @@ -1,99 +0,0 @@ --module('echo_tuple@@main'). --export([run/1]). - --define(red, "\e[31;1m"). --define(grey, "\e[90m"). --define(reset_color, "\e[39m"). --define(reset_all, "\e[0m"). - -run(Module) -> - io:setopts(standard_io, [binary, {encoding, utf8}]), - io:setopts(standard_error, [{encoding, utf8}]), - process_flag(trap_exit, true), - Pid = spawn_link(fun() -> run_module(Module) end), - receive - {'EXIT', Pid, {Reason, StackTrace}} -> - print_error(exit, Reason, StackTrace), - init:stop(1) - end. - -run_module(Module) -> - try - {ok, _} = application:ensure_all_started('echo_tuple'), - erlang:process_flag(trap_exit, false), - Module:main(), - erlang:halt(0) - catch - Class:Reason:StackTrace -> - print_error(Class, Reason, StackTrace), - init:stop(1) - end. - -print_error(Class, Error, Stacktrace) -> - Printed = [ - ?red, "runtime error", ?reset_color, ": ", error_class(Class, Error), ?reset_all, - "\n\n", - error_message(Error), - "\n\n", - error_details(Class, Error), - "stacktrace:\n", - [error_frame(Line) || Line <- refine_first(Error, Stacktrace)] - ], - io:format(standard_error, "~ts~n", [Printed]). - -refine_first(#{gleam_error := _, line := L}, [{M, F, A, [{file, Fi} | _]} | S]) -> - [{M, F, A, [{file, Fi}, {line, L}]} | S]; -refine_first(_, S) -> - S. - -error_class(_, #{gleam_error := panic}) -> "panic"; -error_class(_, #{gleam_error := todo}) -> "todo"; -error_class(_, #{gleam_error := let_assert}) -> "let assert"; -error_class(Class, _) -> ["Erlang ", atom_to_binary(Class)]. - -error_message(#{gleam_error := _, message := M}) -> - M; -error_message(undef) -> - <<"A function was called but it did not exist."/utf8 >>; -error_message({case_clause, _}) -> - <<"No pattern matched in an Erlang case expression."/utf8>>; -error_message({badmatch, _}) -> - <<"An Erlang assignment pattern did not match."/utf8>>; -error_message(function_clause) -> - <<"No Erlang function clause matched the arguments it was called with."/utf8>>; -error_message(_) -> - <<"An error occurred outside of Gleam."/utf8>>. - -error_details(_, #{gleam_error := let_assert, value := V}) -> - ["unmatched value:\n ", print_term(V), $\n, $\n]; -error_details(_, {case_clause, V}) -> - ["unmatched value:\n ", print_term(V), $\n, $\n]; -error_details(_, {badmatch, V}) -> - ["unmatched value:\n ", print_term(V), $\n, $\n]; -error_details(_, #{gleam_error := _}) -> - []; -error_details(error, function_clause) -> - []; -error_details(error, undef) -> - []; -error_details(C, E) -> - ["erlang:", atom_to_binary(C), $(, print_term(E), $), $\n, $\n]. - -print_term(T) -> - try - gleam@string:inspect(T) - catch - _:_ -> io_lib:format("~p", [T]) - end. - -error_frame({?MODULE, _, _, _}) -> []; -error_frame({erl_eval, _, _, _}) -> []; -error_frame({init, _, _, _}) -> []; -error_frame({M, F, _, O}) -> - M1 = string:replace(atom_to_binary(M), "@", "/", all), - [" ", M1, $., atom_to_binary(F), error_frame_end(O), $\n]. - -error_frame_end([{file, Fi}, {line, L} | _]) -> - [?grey, $\s, Fi, $:, integer_to_binary(L), ?reset_all]; -error_frame_end(_) -> - [?grey, " unknown source", ?reset_all]. \ No newline at end of file diff --git a/test-output/cases/echo_tuple/build/dev/erlang/echo_tuple/_gleam_artefacts/gleam@@compile.erl b/test-output/cases/echo_tuple/build/dev/erlang/echo_tuple/_gleam_artefacts/gleam@@compile.erl deleted file mode 100644 index 3e0a645b737..00000000000 --- a/test-output/cases/echo_tuple/build/dev/erlang/echo_tuple/_gleam_artefacts/gleam@@compile.erl +++ /dev/null @@ -1,163 +0,0 @@ -#!/usr/bin/env escript --mode(compile). - -% TODO: Don't concurrently print warnings and errors -% TODO: Some tests - -main(_) -> compile_package_loop(). - -compile_package_loop() -> - case file:read_line(standard_io) of - eof -> ok; - {ok, Line} -> - Chars = unicode:characters_to_list(Line), - {ok, Tokens, _} = erl_scan:string(Chars), - {ok, {Lib, Out, Modules}} = erl_parse:parse_term(Tokens), - case compile_package(Lib, Out, Modules) of - ok -> io:put_chars("gleam-compile-result-ok\n"); - err -> io:put_chars("gleam-compile-result-error\n") - end, - compile_package_loop() - end. - -compile_package(Lib, Out, Modules) -> - IsElixirModule = fun(Module) -> - filename:extension(Module) =:= ".ex" - end, - {ElixirModules, ErlangModules} = lists:partition(IsElixirModule, Modules), - ok = configure_logging(), - ok = add_lib_to_erlang_path(Lib), - ok = filelib:ensure_dir([Out, $/]), - {ErlangOk, _ErlangBeams} = compile_erlang(ErlangModules, Out), - {ElixirOk, _ElixirBeams} = case ErlangOk of - true -> compile_elixir(ElixirModules, Out); - false -> {false, []} - end, - ok = del_lib_from_erlang_path(Lib), - case ErlangOk and ElixirOk of - true -> ok; - false -> err - end. - -compile_erlang(Modules, Out) -> - Workers = start_compiler_workers(Out), - ok = producer_loop(Modules, Workers), - collect_results({true, []}). - -collect_results(Acc = {Result, Beams}) -> - receive - {compiled, Beam} -> collect_results({Result, [Beam | Beams]}); - failed -> collect_results({false, Beams}) - after 0 -> Acc - end. - -producer_loop([], 0) -> - ok; -producer_loop([], Workers) -> - receive - {work_please, _} -> producer_loop([], Workers - 1) - end; -producer_loop([Module | Modules], Workers) -> - receive - {work_please, Worker} -> - erlang:send(Worker, {module, Module}), - producer_loop(Modules, Workers) - end. - -start_compiler_workers(Out) -> - Parent = self(), - NumSchedulers = erlang:system_info(schedulers), - SpawnWorker = fun(_) -> - erlang:spawn_link(fun() -> worker_loop(Parent, Out) end) - end, - lists:foreach(SpawnWorker, lists:seq(1, NumSchedulers)), - NumSchedulers. - -worker_loop(Parent, Out) -> - Options = [report_errors, report_warnings, debug_info, {outdir, Out}], - erlang:send(Parent, {work_please, self()}), - receive - {module, Module} -> - log({compiling, Module}), - case compile:file(Module, Options) of - {ok, ModuleName} -> - Beam = filename:join(Out, ModuleName) ++ ".beam", - Message = {compiled, Beam}, - log(Message), - erlang:send(Parent, Message); - error -> - log({failed, Module}), - erlang:send(Parent, failed) - end, - worker_loop(Parent, Out) - end. - -compile_elixir(Modules, Out) -> - Error = [ - "The program elixir was not found. Is it installed?", - $\n, - "Documentation for installing Elixir can be viewed here:", - $\n, - "https://elixir-lang.org/install.html" - ], - case Modules of - [] -> {true, []}; - _ -> - log({starting, "compiler.app"}), - ok = application:start(compiler), - log({starting, "elixir.app"}), - case application:start(elixir) of - ok -> do_compile_elixir(Modules, Out); - _ -> - io:put_chars(standard_error, [Error, $\n]), - {false, []} - end - end. - -do_compile_elixir(Modules, Out) -> - ModuleBins = lists:map(fun(Module) -> - log({compiling, Module}), - list_to_binary(Module) - end, Modules), - OutBin = list_to_binary(Out), - Options = [{dest, OutBin}], - % Silence "redefining module" warnings. - % Compiled modules in the build directory are added to the code path. - % These warnings result from recompiling loaded modules. - % TODO: This line can likely be removed if/when the build directory is cleaned before every compilation. - 'Elixir.Code':compiler_options([{ignore_module_conflict, true}]), - case 'Elixir.Kernel.ParallelCompiler':compile_to_path(ModuleBins, OutBin, Options) of - {ok, ModuleAtoms, _} -> - ToBeam = fun(ModuleAtom) -> - Beam = filename:join(Out, atom_to_list(ModuleAtom)) ++ ".beam", - log({compiled, Beam}), - Beam - end, - {true, lists:map(ToBeam, ModuleAtoms)}; - {error, Errors, _} -> - % Log all filenames associated with modules that failed to compile. - % Note: The compiler prints compilation errors upon encountering them. - ErrorFiles = lists:usort([File || {File, _, _} <- Errors]), - Log = fun(File) -> - log({failed, binary_to_list(File)}) - end, - lists:foreach(Log, ErrorFiles), - {false, []}; - _ -> {false, []} - end. - -add_lib_to_erlang_path(Lib) -> - code:add_paths(filelib:wildcard([Lib, "/*/ebin"])). - -del_lib_from_erlang_path(Lib) -> - code:del_paths(filelib:wildcard([Lib, "/*/ebin"])). - -configure_logging() -> - Enabled = os:getenv("GLEAM_LOG") /= false, - persistent_term:put(gleam_logging_enabled, Enabled). - -log(Term) -> - case persistent_term:get(gleam_logging_enabled) of - true -> erlang:display(Term), ok; - false -> ok - end. diff --git a/test-output/cases/echo_tuple/build/dev/erlang/echo_tuple/_gleam_artefacts/main.cache b/test-output/cases/echo_tuple/build/dev/erlang/echo_tuple/_gleam_artefacts/main.cache deleted file mode 100644 index 8d8b8b18f52..00000000000 Binary files a/test-output/cases/echo_tuple/build/dev/erlang/echo_tuple/_gleam_artefacts/main.cache and /dev/null differ diff --git a/test-output/cases/echo_tuple/build/dev/erlang/echo_tuple/_gleam_artefacts/main.cache_meta b/test-output/cases/echo_tuple/build/dev/erlang/echo_tuple/_gleam_artefacts/main.cache_meta deleted file mode 100644 index a047fe9d875..00000000000 Binary files a/test-output/cases/echo_tuple/build/dev/erlang/echo_tuple/_gleam_artefacts/main.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_tuple/build/dev/erlang/echo_tuple/_gleam_artefacts/main.cache_warnings b/test-output/cases/echo_tuple/build/dev/erlang/echo_tuple/_gleam_artefacts/main.cache_warnings deleted file mode 100644 index 1b1cb4d44c5..00000000000 Binary files a/test-output/cases/echo_tuple/build/dev/erlang/echo_tuple/_gleam_artefacts/main.cache_warnings and /dev/null differ diff --git a/test-output/cases/echo_tuple/build/dev/erlang/echo_tuple/_gleam_artefacts/main.erl b/test-output/cases/echo_tuple/build/dev/erlang/echo_tuple/_gleam_artefacts/main.erl deleted file mode 100644 index 0c4e8b86ae9..00000000000 --- a/test-output/cases/echo_tuple/build/dev/erlang/echo_tuple/_gleam_artefacts/main.erl +++ /dev/null @@ -1,199 +0,0 @@ --module(main). --compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). - --export([target_specific/0, main/0]). --export_type([wibble/0]). - --type wibble() :: wibble. - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_tuple/src/main.gleam", 13). --spec target_specific() -> {wibble(), integer(), binary()}. -target_specific() -> - echo({wibble, 1, <<"hello"/utf8>>}, "src/main.gleam", 16). - --file("/Users/giacomocavalieri/Documents/progetti/gleam/test-output/cases/echo_tuple/src/main.gleam", 1). --spec main() -> {wibble(), integer(), binary()}. -main() -> - echo({}, "src/main.gleam", 2), - echo({true, 1, <<"hello"/utf8>>}, "src/main.gleam", 3), - target_specific(). - --define(is_lowercase_char(X), (X > 96 andalso X < 123)). --define(is_underscore_char(X), (X == 95)). --define(is_digit_char(X), (X > 47 andalso X < 58)). --define(could_be_record(Tuple), - erlang:is_tuple(Tuple) andalso - erlang:is_atom(erlang:element(1, Tuple)) andalso - erlang:element(1, Tuple) =/= false andalso - erlang:element(1, Tuple) =/= true andalso - erlang:element(1, Tuple) =/= nil -). --define(is_atom_char(C), - (?is_lowercase_char(C) orelse - ?is_underscore_char(C) orelse - ?is_digit_char(C)) -). - --define(grey, "\e[90m"). --define(reset_color, "\e[39m"). - -echo(Value, File, Line) -> - StringLine = erlang:integer_to_list(Line), - StringValue = echo@inspect(Value), - io:put_chars( - standard_error, - [?grey, File, $:, StringLine, ?reset_color, $\n, StringValue, $\n] - ), - Value. - -echo@inspect(Value) -> - case Value of - nil -> "Nil"; - true -> "True"; - false -> "False"; - Int when erlang:is_integer(Int) -> erlang:integer_to_list(Int); - Float when erlang:is_float(Float) -> io_lib_format:fwrite_g(Float); - Binary when erlang:is_binary(Binary) -> inspect@binary(Binary); - Bits when erlang:is_bitstring(Bits) -> inspect@bit_array(Bits); - Atom when erlang:is_atom(Atom) -> inspect@atom(Atom); - List when erlang:is_list(List) -> inspect@list(List); - Map when erlang:is_map(Map) -> inspect@map(Map); - Record when ?could_be_record(Record) -> inspect@record(Record); - Tuple when erlang:is_tuple(Tuple) -> inspect@tuple(Tuple); - Function when erlang:is_function(Function) -> inspect@function(Function); - Any -> ["//erl(", io_lib:format("~p", [Any]), ")"] - end. - -inspect@bit_array(Bits) -> - Pieces = inspect@bit_array_pieces(Bits, []), - Inner = lists:join(", ", lists:reverse(Pieces)), - ["<<", Inner, ">>"]. - -inspect@bit_array_pieces(Bits, Acc) -> - case Bits of - <<>> -> - Acc; - <> -> - inspect@bit_array_pieces(Rest, [erlang:integer_to_binary(Byte) | Acc]); - _ -> - Size = erlang:bit_size(Bits), - <> = Bits, - SizeString = [":size(", erlang:integer_to_binary(Size), ")"], - Piece = [erlang:integer_to_binary(RemainingBits), SizeString], - [Piece | Acc] - end. - -inspect@binary(Binary) -> - case inspect@maybe_utf8_string(Binary, <<>>) of - {ok, InspectedUtf8String} -> - InspectedUtf8String; - {error, not_a_utf8_string} -> - Segments = [erlang:integer_to_list(X) || <> <= Binary], - ["<<", lists:join(", ", Segments), ">>"] - end. - -inspect@atom(Atom) -> - Binary = erlang:atom_to_binary(Atom), - case inspect@maybe_gleam_atom(Binary, none, <<>>) of - {ok, Inspected} -> Inspected; - {error, _} -> ["atom.create_from_string(\"", Binary, "\")"] - end. - -inspect@list(List) -> - case inspect@proper_or_improper_list(List) of - {proper, Elements} -> ["[", Elements, "]"]; - {improper, Elements} -> ["//erl([", Elements, "])"] - end. - -inspect@map(Map) -> - Fields = [ - [<<"#(">>, echo@inspect(Key), <<", ">>, echo@inspect(Value), <<")">>] - || {Key, Value} <- maps:to_list(Map) - ], - ["dict.from_list([", lists:join(", ", Fields), "])"]. - -inspect@record(Record) -> - [Atom | ArgsList] = erlang:tuple_to_list(Record), - Args = lists:join(", ", lists:map(fun echo@inspect/1, ArgsList)), - [echo@inspect(Atom), "(", Args, ")"]. - -inspect@tuple(Tuple) -> - Elements = lists:map(fun echo@inspect/1, erlang:tuple_to_list(Tuple)), - ["#(", lists:join(", ", Elements), ")"]. - -inspect@function(Function) -> - {arity, Arity} = erlang:fun_info(Function, arity), - ArgsAsciiCodes = lists:seq($a, $a + Arity - 1), - Args = lists:join(", ", lists:map(fun(Arg) -> <> end, ArgsAsciiCodes)), - ["//fn(", Args, ") { ... }"]. - -inspect@maybe_utf8_string(Binary, Acc) -> - case Binary of - <<>> -> - {ok, <<$", Acc/binary, $">>}; - <> -> - Escaped = inspect@escape_grapheme(First), - inspect@maybe_utf8_string(Rest, <>); - _ -> - {error, not_a_utf8_string} - end. - -inspect@escape_grapheme(Char) -> - case Char of - $" -> <<$\\, $">>; - $\\ -> <<$\\, $\\>>; - $\r -> <<$\\, $r>>; - $\n -> <<$\\, $n>>; - $\t -> <<$\\, $t>>; - $\f -> <<$\\, $f>>; - X when X > 126, X < 160 -> inspect@convert_to_u(X); - X when X < 32 -> inspect@convert_to_u(X); - Other -> <> - end. - -inspect@convert_to_u(Code) -> - erlang:list_to_binary(io_lib:format("\\u{~4.16.0B}", [Code])). - -inspect@proper_or_improper_list(List) -> - case List of - [] -> - {proper, []}; - [First] -> - {proper, [echo@inspect(First)]}; - [First | Rest] when erlang:is_list(Rest) -> - {Kind, Inspected} = inspect@proper_or_improper_list(Rest), - {Kind, [echo@inspect(First), ", " | Inspected]}; - [First | ImproperRest] -> - {improper, [echo@inspect(First), " | ", echo@inspect(ImproperRest)]} - end. - -inspect@maybe_gleam_atom(Atom, PrevChar, Acc) -> - case {Atom, PrevChar} of - {<<>>, none} -> - {error, nil}; - {<>, none} when ?is_digit_char(First) -> - {error, nil}; - {<<"_", _/binary>>, none} -> - {error, nil}; - {<<"_">>, _} -> - {error, nil}; - {<<"_", _/binary>>, $_} -> - {error, nil}; - {<>, _} when not ?is_atom_char(First) -> - {error, nil}; - {<>, none} -> - inspect@maybe_gleam_atom(Rest, First, <>); - {<<"_", Rest/binary>>, _} -> - inspect@maybe_gleam_atom(Rest, $_, Acc); - {<>, $_} -> - inspect@maybe_gleam_atom(Rest, First, <>); - {<>, _} -> - inspect@maybe_gleam_atom(Rest, First, <>); - {<<>>, _} -> - {ok, Acc}; - _ -> - erlang:throw({gleam_error, echo, Atom, PrevChar, Acc}) - end. - -inspect@uppercase(X) -> X - 32. - diff --git a/test-output/cases/echo_tuple/build/dev/erlang/echo_tuple/ebin/echo_tuple.app b/test-output/cases/echo_tuple/build/dev/erlang/echo_tuple/ebin/echo_tuple.app deleted file mode 100644 index 347e0ba18aa..00000000000 --- a/test-output/cases/echo_tuple/build/dev/erlang/echo_tuple/ebin/echo_tuple.app +++ /dev/null @@ -1,7 +0,0 @@ -{application, echo_tuple, [ - {vsn, "1.0.0"}, - {applications, []}, - {description, ""}, - {modules, [main]}, - {registered, []} -]}. diff --git a/test-output/cases/echo_tuple/build/dev/erlang/gleam_version b/test-output/cases/echo_tuple/build/dev/erlang/gleam_version deleted file mode 100644 index 3e1ad720b13..00000000000 --- a/test-output/cases/echo_tuple/build/dev/erlang/gleam_version +++ /dev/null @@ -1 +0,0 @@ -1.5.0 \ No newline at end of file diff --git a/test-output/cases/echo_tuple/build/dev/javascript/echo_tuple/_gleam_artefacts/main.cache b/test-output/cases/echo_tuple/build/dev/javascript/echo_tuple/_gleam_artefacts/main.cache deleted file mode 100644 index 45ebfb98ea0..00000000000 Binary files a/test-output/cases/echo_tuple/build/dev/javascript/echo_tuple/_gleam_artefacts/main.cache and /dev/null differ diff --git a/test-output/cases/echo_tuple/build/dev/javascript/echo_tuple/_gleam_artefacts/main.cache_meta b/test-output/cases/echo_tuple/build/dev/javascript/echo_tuple/_gleam_artefacts/main.cache_meta deleted file mode 100644 index a047fe9d875..00000000000 Binary files a/test-output/cases/echo_tuple/build/dev/javascript/echo_tuple/_gleam_artefacts/main.cache_meta and /dev/null differ diff --git a/test-output/cases/echo_tuple/build/dev/javascript/echo_tuple/_gleam_artefacts/main.cache_warnings b/test-output/cases/echo_tuple/build/dev/javascript/echo_tuple/_gleam_artefacts/main.cache_warnings deleted file mode 100644 index 1b1cb4d44c5..00000000000 Binary files a/test-output/cases/echo_tuple/build/dev/javascript/echo_tuple/_gleam_artefacts/main.cache_warnings and /dev/null differ diff --git a/test-output/cases/echo_tuple/build/dev/javascript/echo_tuple/gleam.main.mjs b/test-output/cases/echo_tuple/build/dev/javascript/echo_tuple/gleam.main.mjs deleted file mode 100644 index e230911e646..00000000000 --- a/test-output/cases/echo_tuple/build/dev/javascript/echo_tuple/gleam.main.mjs +++ /dev/null @@ -1,2 +0,0 @@ -import { main } from "./main.mjs"; -main(); diff --git a/test-output/cases/echo_tuple/build/dev/javascript/echo_tuple/gleam.mjs b/test-output/cases/echo_tuple/build/dev/javascript/echo_tuple/gleam.mjs deleted file mode 100644 index 197cbbc35d4..00000000000 --- a/test-output/cases/echo_tuple/build/dev/javascript/echo_tuple/gleam.mjs +++ /dev/null @@ -1 +0,0 @@ -export * from "../prelude.mjs"; diff --git a/test-output/cases/echo_tuple/build/dev/javascript/echo_tuple/main.mjs b/test-output/cases/echo_tuple/build/dev/javascript/echo_tuple/main.mjs deleted file mode 100644 index ec3c693bf9e..00000000000 --- a/test-output/cases/echo_tuple/build/dev/javascript/echo_tuple/main.mjs +++ /dev/null @@ -1,133 +0,0 @@ -import { - BitArray as $BitArray, - List as $List, - UtfCodepoint as $UtfCodepoint, - CustomType as $CustomType, -} from "./gleam.mjs"; - -export function target_specific() { - return undefined; -} - -export function main() { - echo([], "src/main.gleam", 2); - echo([true, 1, "hello"], "src/main.gleam", 3); - return target_specific(); -} - -function echo(value, file, line) { - const grey = "\u001b[90m"; - const reset_color = "\u001b[39m"; - const file_line = `${file}:${line}`; - const string_value = echo$inspect(value); - - if (typeof process === "object" && process.stderr?.write) { - // If we're in Node.js, use `stderr` - const string = `${grey}${file_line}${reset_color}\n${string_value}\n`; - process.stderr.write(string); - } else if (typeof Deno === "object") { - // If we're in Deno, use `stderr` - const string = `${grey}${file_line}${reset_color}\n${string_value}\n`; - Deno.stderr.writeSync(new TextEncoder().encode(string)); - } else { - // Otherwise, use `console.log` - // The browser's console.log doesn't support ansi escape codes - const string = `${file_line}\n${string_value}`; - console.log(string); - } - - return value; -} - -function echo$inspectString(str) { - let new_str = '"'; - for (let i = 0; i < str.length; i++) { - let char = str[i]; - if (char == "\n") new_str += "\\n"; - else if (char == "\r") new_str += "\\r"; - else if (char == "\t") new_str += "\\t"; - else if (char == "\f") new_str += "\\f"; - else if (char == "\\") new_str += "\\\\"; - else if (char == '"') new_str += '\\"'; - else if (char < " " || (char > "~" && char < "\u{00A0}")) { - new_str += "\\u{" + char.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0") + "}"; - } else { - new_str += char; - } - } - new_str += '"'; - return new_str; -} - -function echo$inspectDict(map) { - let body = "dict.from_list(["; - let first = true; - map.forEach((value, key) => { - if (!first) body = body + ", "; - body = body + "#(" + echo$inspect(key) + ", " + echo$inspect(value) + ")"; - first = false; - }); - return body + "])"; -} - -function echo$inspectCustomType(record) { - const props = Object.keys(record) - .map((label) => { - const value = echo$inspect(record[label]); - return isNaN(parseInt(label)) ? `${label}: ${value}` : value; - }) - .join(", "); - return props ? `${record.constructor.name}(${props})` : record.constructor.name; -} - -function echo$inspectObject(v) { - const name = Object.getPrototypeOf(v)?.constructor?.name || "Object"; - const props = []; - for (const k of Object.keys(v)) { - props.push(`${echo$inspect(k)}: ${echo$inspect(v[k])}`); - } - const body = props.length ? " " + props.join(", ") + " " : ""; - const head = name === "Object" ? "" : name + " "; - return `//js(${head}{${body}})`; -} - -function echo$inspect(v) { - const t = typeof v; - if (v === true) return "True"; - if (v === false) return "False"; - if (v === null) return "//js(null)"; - if (v === undefined) return "Nil"; - if (t === "string") return echo$inspectString(v); - if (t === "bigint" || t === "number") return v.toString(); - if (Array.isArray(v)) return `#(${v.map(echo$inspect).join(", ")})`; - if (v instanceof $List) return `[${v.toArray().map(echo$inspect).join(", ")}]`; - if (v instanceof $UtfCodepoint) return `//utfcodepoint(${String.fromCodePoint(v.value)})`; - if (v instanceof $BitArray) return `<<${Array.from(v.buffer).join(", ")}>>`; - if (v instanceof $CustomType) return echo$inspectCustomType(v); - if (echo$isDict(v)) return echo$inspectDict(v); - if (v instanceof Set) return `//js(Set(${[...v].map(echo$inspect).join(", ")}))`; - if (v instanceof RegExp) return `//js(${v})`; - if (v instanceof Date) return `//js(Date("${v.toISOString()}"))`; - if (v instanceof Function) { - const args = []; - for (const i of Array(v.length).keys()) args.push(String.fromCharCode(i + 97)); - return `//fn(${args.join(", ")}) { ... }`; - } - return echo$inspectObject(v); -} - -function echo$isDict(value) { - try { - // We can only check if an object is a stdlib Dict if it is one of the - // project's dependencies. - // The `Dict` class is the default export of `stdlib/dict.mjs` - // that we import as `$stdlib$dict`. - return value instanceof $stdlib$dict.default; - } catch { - // If stdlib is not one of the project's dependencies then `$stdlib$dict` - // will not have been imported and the check will throw an exception meaning - // we can't check if something is actually a `Dict`. - return false; - } -} - diff --git a/test-output/cases/echo_tuple/build/dev/javascript/gleam_version b/test-output/cases/echo_tuple/build/dev/javascript/gleam_version deleted file mode 100644 index 3e1ad720b13..00000000000 --- a/test-output/cases/echo_tuple/build/dev/javascript/gleam_version +++ /dev/null @@ -1 +0,0 @@ -1.5.0 \ No newline at end of file diff --git a/test-output/cases/echo_tuple/build/dev/javascript/prelude.mjs b/test-output/cases/echo_tuple/build/dev/javascript/prelude.mjs deleted file mode 100644 index d2adeef273f..00000000000 --- a/test-output/cases/echo_tuple/build/dev/javascript/prelude.mjs +++ /dev/null @@ -1,455 +0,0 @@ -// Values marked with @internal are not part of the public API and may change -// without notice. - -export class CustomType { - withFields(fields) { - let properties = Object.keys(this).map((label) => - label in fields ? fields[label] : this[label], - ); - return new this.constructor(...properties); - } -} - -export class List { - static fromArray(array, tail) { - let t = tail || new Empty(); - for (let i = array.length - 1; i >= 0; --i) { - t = new NonEmpty(array[i], t); - } - return t; - } - - [Symbol.iterator]() { - return new ListIterator(this); - } - - toArray() { - return [...this]; - } - - // @internal - atLeastLength(desired) { - for (let _ of this) { - if (desired <= 0) return true; - desired--; - } - return desired <= 0; - } - - // @internal - hasLength(desired) { - for (let _ of this) { - if (desired <= 0) return false; - desired--; - } - return desired === 0; - } - - // @internal - countLength() { - let length = 0; - for (let _ of this) length++; - return length; - } -} - -// @internal -export function prepend(element, tail) { - return new NonEmpty(element, tail); -} - -export function toList(elements, tail) { - return List.fromArray(elements, tail); -} - -// @internal -class ListIterator { - #current; - - constructor(current) { - this.#current = current; - } - - next() { - if (this.#current instanceof Empty) { - return { done: true }; - } else { - let { head, tail } = this.#current; - this.#current = tail; - return { value: head, done: false }; - } - } -} - -export class Empty extends List {} - -export class NonEmpty extends List { - constructor(head, tail) { - super(); - this.head = head; - this.tail = tail; - } -} - -export class BitArray { - constructor(buffer) { - if (!(buffer instanceof Uint8Array)) { - throw "BitArray can only be constructed from a Uint8Array"; - } - this.buffer = buffer; - } - - // @internal - get length() { - return this.buffer.length; - } - - // @internal - byteAt(index) { - return this.buffer[index]; - } - - // @internal - floatFromSlice(start, end, isBigEndian) { - return byteArrayToFloat(this.buffer, start, end, isBigEndian); - } - - // @internal - intFromSlice(start, end, isBigEndian, isSigned) { - return byteArrayToInt(this.buffer, start, end, isBigEndian, isSigned); - } - - // @internal - binaryFromSlice(start, end) { - return new BitArray(this.buffer.slice(start, end)); - } - - // @internal - sliceAfter(index) { - return new BitArray(this.buffer.slice(index)); - } -} - -export class UtfCodepoint { - constructor(value) { - this.value = value; - } -} - -// @internal -export function toBitArray(segments) { - if (segments.length === 0) { - return new BitArray(new Uint8Array()); - } - - if (segments.length === 1) { - // When there is a single Uint8Array segment, pass it directly to the bit - // array constructor to avoid a copy - if (segments[0] instanceof Uint8Array) { - return new BitArray(segments[0]); - } - - return new BitArray(new Uint8Array(segments)); - } - - // Count the total number of bytes, and check if there are any Uint8Array - // segments - let bytes = 0; - let hasUint8ArraySegment = false; - for (const segment of segments) { - if (segment instanceof Uint8Array) { - bytes += segment.byteLength; - hasUint8ArraySegment = true; - } else { - bytes++; - } - } - - // If there aren't any Uint8Array segments then pass the segments array - // directly to the Uint8Array constructor - if (!hasUint8ArraySegment) { - return new BitArray(new Uint8Array(segments)); - } - - // Copy the segments into a Uint8Array - let u8Array = new Uint8Array(bytes); - let cursor = 0; - for (let segment of segments) { - if (segment instanceof Uint8Array) { - u8Array.set(segment, cursor); - cursor += segment.byteLength; - } else { - u8Array[cursor] = segment; - cursor++; - } - } - - return new BitArray(u8Array); -} - -// @internal -// Derived from this answer https://stackoverflow.com/questions/8482309/converting-javascript-integer-to-byte-array-and-back -export function sizedInt(value, size, isBigEndian) { - if (size < 0) { - return new Uint8Array(); - } - if (size % 8 != 0) { - const msg = `Bit arrays must be byte aligned on JavaScript, got size of ${size} bits`; - throw new globalThis.Error(msg); - } - - const byteArray = new Uint8Array(size / 8); - - // Convert negative number to two's complement representation - if (value < 0) { - value = 2 ** size + value; - } - - if (isBigEndian) { - for (let i = byteArray.length - 1; i >= 0; i--) { - const byte = value % 256; - byteArray[i] = byte; - value = (value - byte) / 256; - } - } else { - for (let i = 0; i < byteArray.length; i++) { - const byte = value % 256; - byteArray[i] = byte; - value = (value - byte) / 256; - } - } - - return byteArray; -} - -// @internal -export function byteArrayToInt(byteArray, start, end, isBigEndian, isSigned) { - let value = 0; - - // Read bytes as an unsigned integer value - if (isBigEndian) { - for (let i = start; i < end; i++) { - value = value * 256 + byteArray[i]; - } - } else { - for (let i = end - 1; i >= start; i--) { - value = value * 256 + byteArray[i]; - } - } - - if (isSigned) { - const byteSize = end - start; - - const highBit = 2 ** (byteSize * 8 - 1); - - // If the high bit is set and this is a signed integer, reinterpret as - // two's complement - if (value >= highBit) { - value -= highBit * 2; - } - } - - return value; -} - -// @internal -export function byteArrayToFloat(byteArray, start, end, isBigEndian) { - const view = new DataView(byteArray.buffer); - - const byteSize = end - start; - - if (byteSize === 8) { - return view.getFloat64(start, !isBigEndian); - } else if (byteSize === 4) { - return view.getFloat32(start, !isBigEndian); - } else { - const msg = `Sized floats must be 32-bit or 64-bit on JavaScript, got size of ${byteSize * 8} bits`; - throw new globalThis.Error(msg); - } -} - -// @internal -export function stringBits(string) { - return new TextEncoder().encode(string); -} - -// @internal -export function codepointBits(codepoint) { - return stringBits(String.fromCodePoint(codepoint.value)); -} - -// @internal -export function sizedFloat(float, size, isBigEndian) { - if (size !== 32 && size !== 64) { - const msg = `Sized floats must be 32-bit or 64-bit on JavaScript, got size of ${size} bits`; - throw new globalThis.Error(msg); - } - - const byteArray = new Uint8Array(size / 8); - - const view = new DataView(byteArray.buffer); - - if (size == 64) { - view.setFloat64(0, float, !isBigEndian); - } else if (size === 32) { - view.setFloat32(0, float, !isBigEndian); - } - - return byteArray; -} - -export class Result extends CustomType { - // @internal - static isResult(data) { - return data instanceof Result; - } -} - -export class Ok extends Result { - constructor(value) { - super(); - this[0] = value; - } - - // @internal - isOk() { - return true; - } -} - -export class Error extends Result { - constructor(detail) { - super(); - this[0] = detail; - } - - // @internal - isOk() { - return false; - } -} - -export function isEqual(x, y) { - let values = [x, y]; - - while (values.length) { - let a = values.pop(); - let b = values.pop(); - if (a === b) continue; - - if (!isObject(a) || !isObject(b)) return false; - let unequal = - !structurallyCompatibleObjects(a, b) || - unequalDates(a, b) || - unequalBuffers(a, b) || - unequalArrays(a, b) || - unequalMaps(a, b) || - unequalSets(a, b) || - unequalRegExps(a, b); - if (unequal) return false; - - const proto = Object.getPrototypeOf(a); - if (proto !== null && typeof proto.equals === "function") { - try { - if (a.equals(b)) continue; - else return false; - } catch {} - } - - let [keys, get] = getters(a); - for (let k of keys(a)) { - values.push(get(a, k), get(b, k)); - } - } - - return true; -} - -function getters(object) { - if (object instanceof Map) { - return [(x) => x.keys(), (x, y) => x.get(y)]; - } else { - let extra = object instanceof globalThis.Error ? ["message"] : []; - return [(x) => [...extra, ...Object.keys(x)], (x, y) => x[y]]; - } -} - -function unequalDates(a, b) { - return a instanceof Date && (a > b || a < b); -} - -function unequalBuffers(a, b) { - return ( - a.buffer instanceof ArrayBuffer && - a.BYTES_PER_ELEMENT && - !(a.byteLength === b.byteLength && a.every((n, i) => n === b[i])) - ); -} - -function unequalArrays(a, b) { - return Array.isArray(a) && a.length !== b.length; -} - -function unequalMaps(a, b) { - return a instanceof Map && a.size !== b.size; -} - -function unequalSets(a, b) { - return ( - a instanceof Set && (a.size != b.size || [...a].some((e) => !b.has(e))) - ); -} - -function unequalRegExps(a, b) { - return a instanceof RegExp && (a.source !== b.source || a.flags !== b.flags); -} - -function isObject(a) { - return typeof a === "object" && a !== null; -} - -function structurallyCompatibleObjects(a, b) { - if (typeof a !== "object" && typeof b !== "object" && (!a || !b)) - return false; - - let nonstructural = [Promise, WeakSet, WeakMap, Function]; - if (nonstructural.some((c) => a instanceof c)) return false; - - return a.constructor === b.constructor; -} - -// @internal -export function remainderInt(a, b) { - if (b === 0) { - return 0; - } else { - return a % b; - } -} - -// @internal -export function divideInt(a, b) { - return Math.trunc(divideFloat(a, b)); -} - -// @internal -export function divideFloat(a, b) { - if (b === 0) { - return 0; - } else { - return a / b; - } -} - -// @internal -export function makeError(variant, module, line, fn, message, extra) { - let error = new globalThis.Error(message); - error.gleam_error = variant; - error.module = module; - error.line = line; - error.function = fn; - // TODO: Remove this with Gleam v2.0.0 - error.fn = fn; - for (let k in extra) error[k] = extra[k]; - return error; -} diff --git a/test-output/cases/echo_tuple/build/packages/packages.toml b/test-output/cases/echo_tuple/build/packages/packages.toml deleted file mode 100644 index e74c18552bb..00000000000 --- a/test-output/cases/echo_tuple/build/packages/packages.toml +++ /dev/null @@ -1 +0,0 @@ -[packages] diff --git a/test-output/cases/echo_tuple/manifest.toml b/test-output/cases/echo_tuple/manifest.toml deleted file mode 100644 index c5d779a3f81..00000000000 --- a/test-output/cases/echo_tuple/manifest.toml +++ /dev/null @@ -1,7 +0,0 @@ -# This file was generated by Gleam -# You typically do not need to edit this file - -packages = [ -] - -[requirements]