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

Single line comments #18

Closed lemol closed 2 months ago

lemol commented 4 years ago

Hi,

Is it possible to render print single-line comments? like:

-- This is a single line comment
rupertlssmith commented 4 years ago

It is not possible as things currently stand. Single line comments are difficult for 2 reasons, I'll explain.

The first is that elm-syntax-dsl uses the AST from stil4m/elm-syntax. When it parses an Elm file, it puts all the single line comments in a list at the File level:

https://package.elm-lang.org/packages/stil4m/elm-syntax/latest/Elm-Syntax-File#File

They are wrapped in Nodes, which give their positions. So I think the elm-syntax printer can reconstruct the file with them put back in place. Seems like an awkward an potentially error prone way of doing things though - what if the position of a comment clashes with the position of some code, if the Elm file is modified by elm-syntax?

The second is that there are very many possible places in the AST that single line comments can go. For example, consider this function application:

-- Before the application
someFun
   -- Comment
   -- Another comment
   arg -- Comment
   arg2 -- Comment
   arg3 -- Comment
   -- And so on

And that is just for function application. Consider the whole AST and all the places where a Maybe Comments is going to have to go.

I think these things could be solved by copying the AST model from elm-syntax into elm-syntax-dsl, so that I can make changes to it and not just use what is provided there. A bit of brainstorming around how best to put single line comments into the AST in a way that avoid proliferating them everywhere might yield a good solution.

For example, if comments are allowed before or after expression, could add a special expression wrapper to the Expression type:

type Expression 
    = .... -- All the normal expression types
    Commented (List String) Expression -- An expression with a single line comment after it.

Would also need the ability to add them at the top level - could add a special case to the Declaration type for that.

rupertlssmith commented 4 years ago

So yes, it is possible in theory to do it, but its a lot more work than it might at first seem.