Credo (or others) enforce guard clauses for all arguments

Does anyone know if there’s a way to enforce the usage of a guard clause for each argument of each function? I want to enforce this style, but I can’t find anything in the Credo documentation about it. Nor can I find any other style checkers which can enforce this.

A while back I wrote an article about the Elixir AST, one of the parts is about building a mini credo: A deep dive into the Elixir AST: Building a static code analyzer (dorgan.ar)

Credo also has it’s own guide to create a custom check: Adding Custom Checks — Credo v1.5.6 (hexdocs.pm)

So basically the idea is that you traverse the AST and when you find a pattern that you don’t like, you create a Credo issue.

The AST for a function definition with guards is something like this:

{:def,_, [
  {:when, _, [
    {:<function name>, _, [arg1, arg2]},
    <ast for guard expressions>
  ]},
  [do: <functon body>]
]}

Where I think it gets complicated is ensuring you have a guard for each argument, considering that function arguments can be patterns, so it gets hairy quite fast. I guess one way is to find all unbounded identifiers in the arguments patterns and assert that they are all present in the identifiers you present in the guards ast.

2 Likes