Skip to content

Handle non-binary bitstring in struct default values #14363

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

Merged
merged 2 commits into from
Mar 25, 2025
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
10 changes: 10 additions & 0 deletions lib/elixir/src/elixir_erl.erl
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,9 @@ elixir_to_erl(Tree, Ann) when is_binary(Tree) ->
%% considers a string in a binary to be encoded in latin1, so the bytes
%% are not changed in any fashion.
{bin, Ann, [{bin_element, Ann, {string, Ann, binary_to_list(Tree)}, default, default}]};
elixir_to_erl(Tree, Ann) when is_bitstring(Tree) ->
Segments = [elixir_to_erl_bitstring_segment(X, Ann) || X <- bitstring_to_list(Tree)],
{bin, Ann, Segments};
elixir_to_erl(Tree, Ann) when is_function(Tree) ->
case (erlang:fun_info(Tree, type) == {type, external}) andalso
(erlang:fun_info(Tree, env) == {env, []}) of
Expand All @@ -115,6 +118,13 @@ elixir_to_erl(Tree, Ann) ->
elixir_to_erl_cons([H | T], Ann) -> {cons, Ann, elixir_to_erl(H, Ann), elixir_to_erl_cons(T, Ann)};
elixir_to_erl_cons(T, Ann) -> elixir_to_erl(T, Ann).

elixir_to_erl_bitstring_segment(Int, Ann) when is_integer(Int) ->
{bin_element, Ann, {integer, Ann, Int}, default, [integer]};
elixir_to_erl_bitstring_segment(Rest, Ann) when is_bitstring(Rest) ->
Size = bit_size(Rest),
<<Int:Size>> = Rest,
{bin_element, Ann, {integer, Ann, Int}, {integer, Ann, Size}, [integer]}.

%% Returns a scope for translation.

scope(_Meta, ExpandCaptures) ->
Expand Down
9 changes: 9 additions & 0 deletions lib/elixir/test/elixir/map_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,15 @@ defmodule MapTest do
assert quoted == {:%, [], [User, {:%{}, [], [{:foo, 1}]}]}
end

test "structs with bitstring defaults" do
defmodule WithBitstring do
defstruct bitstring: <<255, 127::7>>
end

info = Macro.struct_info!(WithBitstring, __ENV__)
assert info == [%{default: <<255, 127::7>>, field: :bitstring}]
end

test "defstruct can only be used once in a module" do
message =
"defstruct has already been called for TestMod, " <>
Expand Down
Loading