Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add erlang.reference_from_dynamic. #56

Merged
merged 5 commits into from
Sep 30, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 25 additions & 2 deletions src/gleam/erlang.gleam
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import gleam/dynamic.{type Dynamic}
import gleam/dynamic.{type DecodeErrors, type Dynamic}
import gleam/erlang/atom.{type Atom}
import gleam/erlang/charlist.{type Charlist}
import gleam/list
Expand Down Expand Up @@ -162,6 +162,29 @@ pub type Reference
@external(erlang, "erlang", "make_ref")
pub fn make_reference() -> Reference

/// Checks to see whether a `Dynamic` value is a Reference, and return the Reference if
/// it is.
///
/// ## Examples
///
/// ```gleam
/// import gleam/dynamic
///
/// reference_from_dynamic(dynamic.from(make_reference()))
/// // -> Ok(Reference)
/// ```
///
/// ```gleam
/// import gleam/dynamic
///
/// reference_from_dynamic(dynamic.from(123))
/// // -> Error([DecodeError(expected: "Reference", found: "Int", path: [])])
/// ```
@external(erlang, "gleam_erlang_ffi", "reference_from_dynamic")
pub fn reference_from_dynamic(
from from: Dynamic,
) -> Result(Reference, DecodeErrors)

/// Returns the path of a package's `priv` directory, where extra non-Gleam
/// or Erlang files are typically kept.
///
Expand All @@ -173,6 +196,6 @@ pub fn make_reference() -> Reference
/// erlang.priv_directory("my_app")
/// // -> Ok("/some/location/my_app/priv")
/// ```
///
///
@external(erlang, "gleam_erlang_ffi", "priv_directory")
pub fn priv_directory(name: String) -> Result(String, Nil)
60 changes: 55 additions & 5 deletions src/gleam/erlang/process.gleam
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import gleam/dynamic.{type DecodeErrors, type Dynamic}
import gleam/erlang.{type Reference}
import gleam/erlang/atom.{type Atom}
import gleam/result
NorbertSzydlik marked this conversation as resolved.
Show resolved Hide resolved
import gleam/string

/// A `Pid` (or Process identifier) is a reference to an Erlang process. Each
Expand Down Expand Up @@ -71,6 +72,55 @@ pub fn new_subject() -> Subject(message) {
Subject(owner: self(), tag: erlang.make_reference())
}

/// Checks to see whether a `Dynamic` value is a Subject, and return the Subject if
/// it is.
///
/// ## Examples
///
/// ```gleam
/// import gleam/dynamic
///
/// subject_from_dynamic(dynamic.from(new_subject()))
/// // -> Ok(Subject))
/// ```
///
/// ```gleam
/// import gleam/dynamic
///
/// subject_from_dynamic(dynamic.from(123))
/// // -> Error([
/// // DecodeError(expected: "Tuple of 3 elements", found: "Int", path: []),
/// // ])
/// ```
pub fn subject_from_dynamic(
NorbertSzydlik marked this conversation as resolved.
Show resolved Hide resolved
from from: Dynamic,
) -> Result(Subject(message), DecodeErrors) {
use from <- result.try(
from
|> dynamic.tuple3(
atom.from_dynamic,
pid_from_dynamic,
erlang.reference_from_dynamic,
),
)

let #(record_atom, pid, tag) = from
let assert Ok(subject_atom) = atom.from_string("subject")
case record_atom == subject_atom {
True -> {
Ok(Subject(owner: pid, tag: tag))
}
False ->
Error([
dynamic.DecodeError(
expected: string.inspect(subject_atom),
found: string.inspect(record_atom),
path: ["0"],
),
])
}
}

/// Get the owner process for a `Subject`. This is the process that created the
/// `Subject` and will receive messages sent with it.
///
Expand Down Expand Up @@ -147,12 +197,12 @@ pub fn receive(
/// let int_subject = new_subject()
/// let float_subject = new_subject()
/// send(int_subject, 1)
///
///
/// let selector =
/// new_selector()
/// |> selecting(int_subject, int.to_string)
/// |> selecting(float_subject, float.to_string)
///
///
/// select(selector, 10)
/// // -> Ok("1")
/// ```
Expand Down Expand Up @@ -731,7 +781,7 @@ pub fn trap_exits(a: Bool) -> Nil
/// - The process for the pid no longer exists.
/// - The name has already been registered.
/// - The process already has a name.
/// - The name is the atom `undefined`, which is reserved by Erlang.
/// - The name is the atom `undefined`, which is reserved by Erlang.
///
@external(erlang, "gleam_erlang_ffi", "register_process")
pub fn register(pid: Pid, name: Atom) -> Result(Nil, Nil)
Expand All @@ -756,13 +806,13 @@ pub fn named(name: Atom) -> Result(Pid, Nil)
/// it is.
///
/// ## Examples
///
///
/// ```gleam
/// import gleam/dynamic
/// from_dynamic(dynamic.from(process.self()))
/// // -> Ok(process.self())
/// ```
///
///
/// ```gleam
/// from_dynamic(dynamic.from(123))
/// // -> Error([DecodeError(expected: "Pid", found: "Int", path: [])])
Expand Down
18 changes: 12 additions & 6 deletions src/gleam_erlang_ffi.erl
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
-module(gleam_erlang_ffi).
-export([
atom_from_dynamic/1, rescue/1, atom_from_string/1, get_line/1,
ensure_all_started/1, sleep/1, os_family/0, sleep_forever/0,
ensure_all_started/1, sleep/1, os_family/0, sleep_forever/0,
get_all_env/0, get_env/1, set_env/2, unset_env/1, demonitor/1,
new_selector/0, link/1, insert_selector_handler/3, select/1, select/2,
trap_exits/1, map_selector/2, merge_selector/2, flush_messages/0,
priv_directory/1, connect_node/1, register_process/2, unregister_process/1,
process_named/1, identity/1, pid_from_dynamic/1, port_from_dynamic/1
process_named/1, identity/1, pid_from_dynamic/1, reference_from_dynamic/1,
port_from_dynamic/1
]).

-spec atom_from_string(binary()) -> {ok, atom()} | {error, atom_not_loaded}.
Expand All @@ -25,6 +26,11 @@ pid_from_dynamic(Data) when is_pid(Data) ->
pid_from_dynamic(Data) ->
{error, [{decode_error, <<"Pid">>, gleam@dynamic:classify(Data), []}]}.

reference_from_dynamic(Data) when is_reference(Data) ->
{ok, Data};
reference_from_dynamic(Data) ->
{error, [{decode_error, <<"Reference">>, gleam@dynamic:classify(Data), []}]}.

port_from_dynamic(Data) when is_port(Data) ->
{ok, Data};
port_from_dynamic(Data) ->
Expand Down Expand Up @@ -130,7 +136,7 @@ select({selector, Handlers}, Timeout) ->
Msg when is_map_key({element(1, Msg), tuple_size(Msg)}, Handlers) ->
Fn = maps:get({element(1, Msg), tuple_size(Msg)}, Handlers),
{ok, Fn(Msg)};

Msg when AnythingHandler =/= undefined ->
{ok, AnythingHandler(Msg)}
after Timeout ->
Expand All @@ -141,7 +147,7 @@ demonitor({_, Reference}) ->
erlang:demonitor(Reference, [flush]).

link(Pid) ->
try
try
erlang:link(Pid)
catch
error:_ -> false
Expand All @@ -158,7 +164,7 @@ flush_messages() ->

priv_directory(Name) ->
try erlang:binary_to_existing_atom(Name) of
Atom ->
Atom ->
case code:priv_dir(Atom) of
{error, _} -> {error, nil};
Path -> {ok, unicode:characters_to_binary(Path)}
Expand All @@ -175,7 +181,7 @@ connect_node(Node) ->
end.

register_process(Pid, Name) ->
try
try
true = erlang:register(Name, Pid),
{ok, nil}
catch
Expand Down
95 changes: 95 additions & 0 deletions test/gleam/erlang/process_test.gleam
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import gleam/dynamic.{DecodeError}
import gleam/erlang
import gleam/erlang/atom
import gleam/erlang/process.{ProcessDown}
import gleam/float
Expand Down Expand Up @@ -568,3 +569,97 @@ pub fn pid_from_dynamic_test() {
|> dynamic.from
|> process.pid_from_dynamic
}

type TestType(unused) {
TestSimilar(owner: process.Pid, tag: erlang.Reference)
TestDifferent(unused, unused)
Subject(Int, String)
}

pub fn subject_from_dynamic_test() {
let subject = process.new_subject()
let assert Ok(sub_from_dynamic) =
subject
|> dynamic.from
|> process.subject_from_dynamic
let assert True = subject == sub_from_dynamic

let assert Error([
DecodeError(expected: "Subject", found: "TestSimilar", path: ["0"]),
]) =
TestSimilar(process.self(), erlang.make_reference())
|> dynamic.from
|> process.subject_from_dynamic

let assert Error([
DecodeError(expected: "Pid", found: "Int", path: ["1"]),
DecodeError(expected: "Reference", found: "Int", path: ["2"]),
]) =
TestDifferent(1, 2)
|> dynamic.from
|> process.subject_from_dynamic

let assert Error([
DecodeError(expected: "Pid", found: "Int", path: ["1"]),
DecodeError(expected: "Reference", found: "String", path: ["2"]),
]) =
Subject(123, "abc")
|> dynamic.from
|> process.subject_from_dynamic

let assert Error([
DecodeError(expected: "Tuple of 3 elements", found: "Int", path: []),
]) =
1
|> dynamic.from
|> process.subject_from_dynamic

let assert Error([
DecodeError(
expected: "Tuple of 3 elements",
found: "Tuple of 1 elements",
path: [],
),
]) =
#(1)
|> dynamic.from
|> process.subject_from_dynamic

let assert Error([DecodeError(expected: "Atom", found: "Int", path: ["0"])]) =
#(1, process.self(), erlang.make_reference())
|> dynamic.from
|> process.subject_from_dynamic
}

pub fn subject_from_dynamic_send_receive_test() {
let subject = process.new_subject()
let assert Ok(sub_from_dynamic) =
subject
|> dynamic.from
|> process.subject_from_dynamic
let assert True = subject == sub_from_dynamic

let assert Ok(another_sub_from_dynamic) =
subject
|> dynamic.from
|> process.subject_from_dynamic
let assert True = subject == another_sub_from_dynamic

process.start(
fn() { process.send(another_sub_from_dynamic, process.self()) },
linked: True,
)
let assert Ok(child_pid) = process.receive(sub_from_dynamic, 5)
let assert True = child_pid != process.self()

process.start(
fn() { process.send(sub_from_dynamic, process.self()) },
linked: True,
)
let assert Ok(child_pid) = process.receive(subject, 5)
let assert True = child_pid != process.self()

process.start(fn() { process.send(subject, process.self()) }, linked: True)
let assert Ok(child_pid) = process.receive(another_sub_from_dynamic, 5)
let assert True = child_pid != process.self()
}
23 changes: 22 additions & 1 deletion test/gleam/erlang_test.gleam
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import gleam/dynamic
import gleam/dynamic.{DecodeError}
import gleam/erlang.{UnknownApplication}
import gleam/erlang/atom
import gleam/iterator
Expand Down Expand Up @@ -49,6 +49,27 @@ pub fn make_reference_test() {
|> iterator.run
}

pub fn reference_from_dynamic_test() {
let reference = erlang.make_reference()
let assert Ok(reference_from_dynamic) =
reference
|> dynamic.from
|> erlang.reference_from_dynamic
let assert True = reference == reference_from_dynamic

let assert Error([DecodeError(expected: "Reference", found: "Int", path: [])]) =
123
|> dynamic.from
|> erlang.reference_from_dynamic

let assert Error([
DecodeError(expected: "Reference", found: "String", path: []),
]) =
"abc"
|> dynamic.from
|> erlang.reference_from_dynamic
}

pub fn priv_directory_test() {
let assert Error(Nil) = erlang.priv_directory("unknown_application")

Expand Down