elixir icon indicating copy to clipboard operation
elixir copied to clipboard

Macro.to_string adds redundant parentheses around binary operators

Open pminten opened this issue 13 years ago • 2 comments

(quote do: 1 | 2 | 3 | 4) |> Macro.to_string

Returns "((1 | 2) | 3) | 4"

I use Macro.to_string for formatting the type specifications and the extra parenthesis in some cases make those hard to parse for humans, for example the type Inspect.Algebra.t() is printed as t() :: (((((:doc_nil | doc_cons_t()) | doc_nest_t()) | doc_break_t()) | doc_group_t()) | binary()) instead of t() :: :doc_nil | doc_const_t() | doc_nest_t() | doc_break_t() | doc_group_t() | binary()

Maybe relying on Macro.to_string for user facing output (as opposed to quick development tests) is wrong but the logic required for constructing source code from an AST is a bit subtle so I'd hate to have to replicate it.

pminten avatar Aug 15 '13 09:08 pminten

We should definitely improve Macro.to_string/1 to take operator associativity and precedence into account. We could start by simply not adding parentheses when the same operator is used over and over again, according to its associativity (the associativity check is important, as (1 | 2) | 3 may be different than 1 | (2 | 3)).

We could later expand it to account for precedence as well. The table with associativity and precedence can be found here: https://github.com/elixir-lang/elixir/blob/master/lib/elixir/src/elixir_parser.yrl#L48-L68

josevalim avatar Aug 15 '13 09:08 josevalim

Hmm, doesn't look like it's too spectacularly complicated, op_to_string currently just adds parentheses in all cases and will need to take into account precedence and associativity. I'll take a stab at it later today.

pminten avatar Aug 15 '13 09:08 pminten