parameters.ex (2134B)
1 defmodule Credo.Code.Parameters do 2 @moduledoc """ 3 This module provides helper functions to analyse the parameters taken by a 4 function. 5 """ 6 7 @def_ops [:def, :defp, :defmacro] 8 9 @doc "Returns the parameter count for the given function's AST" 10 def count(nil), do: 0 11 12 for op <- @def_ops do 13 def count({unquote(op), _, arguments}) when is_list(arguments) do 14 case List.first(arguments) do 15 {_atom, _meta, nil} -> 16 0 17 18 {_atom, _meta, list} -> 19 Enum.count(list) 20 21 _ -> 22 0 23 end 24 end 25 end 26 27 @doc "Returns the names of all parameters for the given function's AST" 28 def names(nil), do: nil 29 30 for op <- @def_ops do 31 def names({unquote(op), _meta, arguments}) when is_list(arguments) do 32 arguments 33 |> List.first() 34 |> get_param_names 35 end 36 end 37 38 defp get_param_names({:when, _meta, arguments}) do 39 arguments 40 |> List.first() 41 |> get_param_names 42 end 43 44 defp get_param_names(arguments) when is_tuple(arguments) do 45 arguments 46 |> Tuple.to_list() 47 |> List.last() 48 |> Enum.map(&get_param_name/1) 49 |> Enum.reject(&is_nil/1) 50 end 51 52 defp get_param_name({:"::", _, [var, _type]}) do 53 get_param_name(var) 54 end 55 56 defp get_param_name({:<<>>, _, arguments}) do 57 arguments 58 |> Enum.map(&get_param_name/1) 59 |> Enum.reject(&is_nil/1) 60 end 61 62 defp get_param_name({:=, _, arguments}) do 63 arguments 64 |> Enum.map(&get_param_name/1) 65 |> Enum.reject(&is_nil/1) 66 end 67 68 defp get_param_name({:%, _, [{:__aliases__, _meta, _mod_list}, {:%{}, _meta2, arguments}]}) do 69 get_param_name(arguments) 70 end 71 72 defp get_param_name({:%{}, _, arguments}) do 73 get_param_name(arguments) 74 end 75 76 defp get_param_name({:\\, _, arguments}) do 77 Enum.find_value(arguments, &get_param_name/1) 78 end 79 80 defp get_param_name(list) when is_list(list) do 81 list 82 |> Enum.map(fn {atom, tuple} when is_atom(atom) and is_tuple(tuple) -> 83 get_param_name(tuple) 84 end) 85 |> Enum.reject(&is_nil/1) 86 end 87 88 defp get_param_name({name, _, nil}) when is_atom(name), do: name 89 90 defp get_param_name(_) do 91 nil 92 end 93 end