the-sett / elm-syntax-dsl

A DSL for creating Elm syntax trees and pretty printing Elm source code.
BSD 3-Clause "New" or "Revised" License
20 stars 4 forks source link

Add parenthesis based on operator precedence. #9

Closed rupertlssmith closed 2 years ago

rupertlssmith commented 5 years ago

The DSL builds an AST so all the information should be availabnle for deciding whether to insert parenthesis around lower precendence operators that occur as sub-expressions within higher precendene expressions, or equal precenence expressions but with the wrong direction of associativity.

So

import Elm.CodeGen as CG
CG.opApply "*" (CG.opApply "+" (CG.int 1) (CG.int 2)) (CG.int 3)

Should render as:

(1 + 2) * 3

This logic would be put in the pretty printer, in the adjustExpressionParentheses function or possibly in prettyOperatorApplication.

Other cases where parens can automatically be inserted in expressions?