Skip to content

No API to retrieve enforced_keys on a struct #14500

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

Closed
lukaszsamson opened this issue May 17, 2025 · 5 comments
Closed

No API to retrieve enforced_keys on a struct #14500

lukaszsamson opened this issue May 17, 2025 · 5 comments

Comments

@lukaszsamson
Copy link
Contributor

Elixir and Erlang/OTP versions

any

Operating system

any

Current behavior

When a language server is returning completions with struct keys it would be nice to highlight the enforced ones. There is currently no API to retrieve that info. The @enforce_keys attribute is compile time only, there is no trace of that left in EEP48 docs.

Expected behavior

A metadata entry with enforced keys in documentation for the :__struct__ function

@josevalim
Copy link
Member

It is available on __info__(:struct) also based if the field has a default or not.

@lukaszsamson
Copy link
Contributor Author

If so then it's not what I'd expect to see

Interactive Elixir (1.18.3) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> Date.__info__(:struct)
[
  %{default: nil, field: :year},
  %{default: nil, field: :month},
  %{default: nil, field: :day},
  %{default: Calendar.ISO, field: :calendar}
]
iex(2)> %Date{}
** (ArgumentError) the following keys must also be given when building struct Date: [:year, :month, :day]
    (elixir 1.18.3) expanding struct: Date.__struct__/1
    iex:2: (file)

@josevalim
Copy link
Member

Hrm, could it be main only or am I hallucinating?

@olunusib
Copy link

Seems there used to be a required boolean key, but it was removed in e3bad83#diff-2749d1ae144d00522b8cc4c216006f3cf7ca6eeb79b4d3f70bc6124a09f861a3L216-R216? With an older version:

Interactive Elixir (1.17.3) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> Date.__info__(:struct)
[
  %{field: :year, required: true},
  %{field: :month, required: true},
  %{field: :day, required: true},
  %{field: :calendar, required: false}
]

@josevalim
Copy link
Member

Ah, thank you, that's it. We have plans to make the default key optional once we introduce typed structs. That's because once we introduce typed structs, a required field should not really have a default value, otherwise if you say field :age, integer(), required: true and then it defaults to nil, it means the type is actually integer() or nil. Therefore this will be tackled by #13881.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

3 participants