Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
17 changes: 15 additions & 2 deletions lib/imp/signature/field.ex
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ defmodule Imp.Signature.Field do
end

def new(name, kind) when is_atom(name) do
name = normalize_name(name)
%__MODULE__{name: name, kind: normalize_kind(kind), prefix: infer_prefix(name)}
end

Expand Down Expand Up @@ -172,10 +173,22 @@ defmodule Imp.Signature.Field do
end
end

# `nil`, `true` and `false` are atoms but not names: a field given one of
# them as an atom is refused, and one written as text keeps its text, so
# `"nil: string -> a"` has a field named "nil" that saves and loads as "nil".
defp normalize_name(name) when name in [nil, true, false] do
raise ArgumentError,
"Imp.Signature.Field.new/2 expects a field name, got: #{inspect(name)}"
end

defp normalize_name(name) when is_atom(name), do: name

defp normalize_name(name) when is_binary(name),
do: name |> String.trim() |> existing_atom_or_string()
defp normalize_name(name) when is_binary(name) do
case String.trim(name) do
literal when literal in ["nil", "true", "false"] -> literal
trimmed -> existing_atom_or_string(trimmed)
end
end

defp normalize_name(name) do
raise ArgumentError,
Expand Down
16 changes: 16 additions & 0 deletions test/property_invariants_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,22 @@ defmodule PropertyInvariantsTest do
end
end

test "fields named nil, true and false keep their names through dump and load" do
signature = Imp.signature("nil: string, true: string -> false: string")
loaded = signature |> Imp.Signature.dump() |> Jason.encode!() |> Jason.decode!()
loaded = Imp.Signature.load!(loaded)

assert Imp.Signature.input_names(signature) == ["nil", "true"]
assert Imp.Signature.input_names(loaded) == ["nil", "true"]
assert Imp.Signature.output_names(loaded) == ["false"]
end

test "a field name given as the atom nil is refused" do
assert_raise ArgumentError, ~r/expects a field name, got: nil/, fn ->
Imp.Signature.Field.new(nil, :input)
end
end

property "signature dump/load round-trips the serialized contract" do
check all(spec <- signature_spec(), max_runs: 100) do
signature = Imp.signature(spec)
Expand Down
Loading