Skip to content

Show list opts when inspecting Regex #11991

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 1 commit into from
Jul 18, 2022
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/lib/inspect.ex
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,16 @@ defimpl Inspect, for: Float do
end

defimpl Inspect, for: Regex do
def inspect(regex = %{opts: regex_opts}, opts) when is_list(regex_opts) do
concat([
"Regex.compile!(",
Inspect.BitString.inspect(regex.source, opts),
", ",
Inspect.List.inspect(regex_opts, opts),
")"
])
end

def inspect(regex, opts) do
{escaped, _} =
regex.source
Expand Down
7 changes: 6 additions & 1 deletion lib/elixir/lib/regex.ex
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ defmodule Regex do

defstruct re_pattern: nil, source: "", opts: "", re_version: ""

@type t :: %__MODULE__{re_pattern: term, source: binary, opts: binary}
@type t :: %__MODULE__{re_pattern: term, source: binary, opts: binary | list(atom)}

defmodule CompileError do
defexception message: "regex could not be compiled"
Expand Down Expand Up @@ -203,13 +203,18 @@ defmodule Regex do
defp compile(source, opts, doc_opts, version) do
case :re.compile(source, opts) do
{:ok, re_pattern} ->
doc_opts = format_doc_opts(doc_opts, opts)
{:ok, %Regex{re_pattern: re_pattern, re_version: version, source: source, opts: doc_opts}}

error ->
error
end
end

defp format_doc_opts(_doc_opts = "", _opts = []), do: ""
defp format_doc_opts(_doc_opts = "", opts), do: opts
defp format_doc_opts(doc_opts, _opts), do: doc_opts

@doc """
Compiles the regular expression and raises `Regex.CompileError` in case of errors.
"""
Expand Down
2 changes: 2 additions & 0 deletions lib/elixir/test/elixir/inspect_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -863,6 +863,8 @@ defmodule Inspect.OthersTest do
assert inspect(~r<\a\b\d\e\f\n\r\s\t\v/>) == "~r/\\a\\b\\d\\e\\f\\n\\r\\s\\t\\v\\//"
assert inspect(~r" \\/ ") == "~r/ \\\\\\/ /"
assert inspect(~r/hi/, syntax_colors: [regex: :red]) == "\e[31m~r/hi/\e[0m"

assert inspect(Regex.compile!("foo", [:caseless])) == ~S'Regex.compile!("foo", [:caseless])'
end

test "inspect_fun" do
Expand Down