Retain comments in field parser - #11252
Conversation
andreabedini
left a comment
There was a problem hiding this comment.
Thank you for taking on this work. I think adding a Comment constructor to Field is not a good design. It modifies the meaning of the type (and indeed this forces you to make functions like elementInLayoutContext return [Fields]).
I think this has been already discussed before: we have the ann parameter which can be used to keep hold on the comments. E.g.
data Comment ann = Comment !ann !ByteString
type FieldWithComments ann = Field ([Comment ann], ann)In this design each Field carries the comments preceding it, annotated with their position. An extra annotation marks the position of the field itself. Any comment at the end of the file would need to be captured separately.
This is already the practice of few packages developed by the community. Is there a reason to deviate from this?
|
Here's a preliminary benchmark done with Upstream: ~/r/haskell/cabal λ lts-18.28
$ hyperfine --runs 30 './validate.sh --partial-hackage-tests'
Benchmark 1: ./validate.sh --partial-hackage-tests
Time (mean ± σ): 203.400 s ± 21.816 s [User: 150.484 s, System: 39.487 s]
Range (min … max): 183.805 s … 277.905 s 30 runsThis branch: …/wt/haskell/cabal/exact-pp-leana λ lts-18.28
$ hyperfine --runs 30 './validate.sh --partial-hackage-tests'
Benchmark 1: ./validate.sh --partial-hackage-tests
Time (mean ± σ): 199.168 s ± 10.540 s [User: 156.373 s, System: 39.818 s]
Range (min … max): 184.443 s … 242.563 s 30 runsThank you for your response Andrea, I'll write up a response and get back to you soon :) |
|
Thank you for your comment @andreabedini :)
That looks very interesting, but how would I deal with files that are just comments? To the point of view of readFields they should be valid yet we would have no I do think your model is very interesting so if you have the time to, please show working PR against mine so we can simply merge it in 🙏
Could you elaborate which packages are these? I would love to have more insight on how people solve similar problems. Are there other design issues that needs to be addressed ? |
Are they valid Cabal files if there is nothing but comments? I don't think so.
For instance, annotateFieldsWithSource :: ByteString -> [Field Position] -> [Field ByteString]which annotates each field with its source including all adjacent comments. It can be modified to return |
| match _ = Nothing | ||
|
|
||
| -- | Collect comments into a map. The second field of the output will have no comment | ||
| extractComments :: Ord ann => [Field ann] -> (Map.Map ann ByteString, [Field ann]) |
There was a problem hiding this comment.
Could you possibly outline how the output of this function is supposed to be used? Now that we detached comments from fields, how do we reconstruct the original document? How do we do it if [Field ann] is programmatically updated (say, adding or removing elements)?
There was a problem hiding this comment.
Could you possibly outline how the output of this function is supposed to be used?
This function recursively extracts the comments from the fields (the updated design variant does the same thing, albeit being more concise).
It is used to extract the comments out right before running the parseFieldGrammar parser in src/Distribution/PackageDescription/Parsec.hs. This allows us to not change the grammar and be able to directly inject the comments into the GenericPackageDescription.
Now that we detached comments from fields, how do we reconstruct the original document?
We can't yet. Following Jappie's proposal, we need to store the exact position of each field as a map (called exactPositions) indexed by the path in the rose tree (typed [NameSpace], a list of path segments). And then we will have the right information to construct the exact printer.
How do we do it if [Field ann] is programmatically updated (say, adding or removing elements)?
To quote Jappie:
The issue for addition is that you now have to invent exact positions. for removal, if it involves a line, you've to fix up all following lines, (and it has to know something was removed).
I haven't thought about this thoroughly because it's out of scope of this PR, but it should be very much feasible.
Pretty sure you need at minimum |
|
Hi friends, thanks for all your responses. Leana needs some time to read up on the exact proposal to see how it all fits together before replying. |
|
Cabal is one of the toughest code bases I ever worked on, so I'm quite amazed by Leana making progress so quickly! |
|
Thank you Bodigrim and Jappie for your kind words! That means a lot to me, I'm glad to be on the right track. I have started (and completed) to rewrite my PR using Andrea's approach.
Good to know. Currently the top level parser drops the comments consumed if there are no fields to attach them to. Let me know what you think about the change :) |
|
Here are the benchmark results. The baseline has been rerun because I did these ones on a VPS machine, and they are not comparable to the last ones I ran on my machine. # baseline
leana@Ubuntu-2404-noble-amd64-base:~/cabal$ hyperfine './validate.sh --partial-hackage-tests'
Benchmark 1: ./validate.sh --partial-hackage-tests
Time (mean ± σ): 253.353 s ± 9.520 s [User: 196.642 s, System: 60.881 s]
Range (min … max): 241.649 s … 271.207 s 10 runs
# this PR
leana@Ubuntu-2404-noble-amd64-base:~/cabal$ hyperfine --setup "./validate.sh --partial-hackage-tests" "./validate.sh --partial-hackage-tests"
Benchmark 1: ./validate.sh --partial-hackage-tests
Time (mean ± σ): 253.163 s ± 7.451 s [User: 196.432 s, System: 58.507 s]
Range (min … max): 239.373 s … 266.656 s 10 runs |
In my prototype I have replaced Where the extra annotation is for anything coming after the last field.
In addition to @Bodigrim's
I am available to discuss and support her effort. @leana8959 I'll reach out privately.
I warmly second this! |
|
@leana8959, @andreabedini: how is the private communication going? We are interested too! Could we help somehow? |
|
for clarity: These parser changes are ready for review as far as leana and me are concerned, meanwhile we've moved over to import stanza retention in GenericPackageDescription (they currently get merged into the stanza's). This is an independent change of the parser changes here. After that we can start on exact print propper. |
Please don't. A lot of code wants an elaborated (= stripped down of syntactic convenience) representation of package description, and GPD serves that now. Your parsing changes leak down the pipeline where they shouldn't. E.g. things like solver works with GPD, and it really shouldn't care about whether import stanzas were used to declare a package or not. |
|
This PR isn't about that, |
|
This PR does add , exactComments :: ExactComments Positionfield to GPD. I don't see a point of having comments in GPD. (As noted in tests, it "breaks" equality) |
|
@phadej Indeed, I have added a newtype around |
|
I understand, the authors would like to get reviews for this PR. If this is so, please, squash the commit history. For the size of PR: a good part of the changes are test-suite changes, it seems. I don't think they have to be extracted into separate PR or even separate commits (because having commits that don't pass CI individually may be cumbersome in the future, for git-bisecting and alike). |
|
@mpickering can you take a high-level look at the design in this PR and tell us your opinion? The gist of it is: and then many parsing utilities that used to return -parseGenericPackageDescription'
+parseAnnotatedGenericPackageDescription'
:: Maybe CabalSpecVersion
-> [LexWarning]
-> Maybe Int
- -> [Field Position]
- -> ParseResult src GenericPackageDescription
-parseGenericPackageDescription' scannedVer lexWarnings utf8WarnPos fs = do
+ -> [Field (WithComments Position)]
+ -> ParseResult src AnnotatedGenericPackageDescription
+parseAnnotatedGenericPackageDescription' scannedVer lexWarnings utf8WarnPos fs = do |
|
One particular thing that bothers me is that clients will have to call Any thoughts? Meta-comment: I looked through the tech proposal again, and there doesn't appear to be a technical description of a solution for this particular comments issue. It is totally fine, because the proposal would turn into a foliant at that level of detail. Neveretheless, I wish that, before doing all the technical work in this PR, the authors had discussed the actual technical solution for the particular issue (like preserving comments; others are listed in the tech proposal) on the Cabal bug tracker (here). |
@ulysses4ever Are there some rule of thumb to squash my commits? I already went through the history once this morning and split out all changes that touch the testsuite into one commit. |
26f34ae to
7751130
Compare
|
I cleaned up everything and made sure the test passes, this is ready for review! |
|
@jappeace @leana8959 should we remove the needs-review label for now given #11227 (comment) ? |
296f3b8 to
b8d6985
Compare
|
Might this be a good moment for a (re-)review? |
|
@Mikolaj yes! I wanted to bring this up again in the cabal meeting. |
7a2cef0 to
ac30e8f
Compare
| commentsAfter p = do | ||
| x <- p | ||
| postCmts <- many tokComment | ||
| pure $ fmap (WithComments postCmts) x |
There was a problem hiding this comment.
Could it be commentsAfter p = flip WithComments <$> p <*> many tokComment?
The real question though is: if comments in WithComments are the ones following and not preceding, should not they go to the second field instead of the first one?
There was a problem hiding this comment.
Could it be
commentsAfter p = flip WithComments <$> p <*> many tokComment?
Indeed, nice catch.
It would need to be flip (fmap . WithComments) <$> p <*> many tokComment but I feel like it's less readable.
The real question though is: if comments in WithComments are the ones following and not preceding, should not they go to the second field instead of the first one
It is not that easy, because when we parse something with trailing comments, we don't yet know if there are fields that follow. For example, when parsing some field lines, we don't know if the comments we got are for this fieldline or if there are following fields and the comments belong there.
To implement what you meant (on which I agree is the "better" outcome), I'd need to guess that there's a following field, and then backtrack to attaching to current field line if I guessed wrong. Personally I think that obfuscates the flow of the parser and may cause obscure bugs that only manifest when user writes comments a certain way. Considering we don't anchor comments to AST nodes like haddock does and comments attachments to nodes aren't specified at all 1, I think this is reasonable.
In case in the future we need to attach comments to the later field (should it exist), I also think it's a better idea to implement that with a function that post-processes the fields, just to keep the parser simple.
Footnotes
-
It is possible to give comments that have ambiguous attachments like the following.
↩build-depends: foo -- some comments exposed-modules: Main
There was a problem hiding this comment.
Perhaps I was not clear what I meant. When we have WithComments "foo" "bar", does it stand for foo -- bar or for --bar \n foo?
There was a problem hiding this comment.
Interesting question. The current semantic is "around", so we can't tell without inspecting the Position annotation. Do you think it'd be useful to make WithComments to have two fields, one for leading comments and one for trailing comments?
There was a problem hiding this comment.
I think I'm missing something fundamental here. If the current semantics is "around" then what is stored where? Is it the case that both preceding and following comments will be elements of the list justComments :: ![Comment ann]? Could there be less than two or more than two elements? Is the order of elements of the list predetermined or can one put them in any order, even if not matching locations?
I think having priorComment :: Comment ann and followingComment :: Comment ann would be handy and self-explanatory, if it is achievable.
There was a problem hiding this comment.
In cabal the lexer emits a Comment token for a line comment. Also, all comments are line comments. This is why the type is [Comment ann] instead of Comment ann.
I also think it might make manipulating the comments a bit easier during printing, I'll do that. Thanks for the suggestion! I'll keep you updated.
1fb66a2 to
d48d350
Compare
| -- This has the benefit of providing more exact error message by having more | ||
| -- knowledge about what symbol should follow in the input stream. | ||
| -- | ||
| -- This lexer never switches to some of the states itself. |
There was a problem hiding this comment.
To which states the lexer can never switch itself? On a brief inspection I didn't find any.
There was a problem hiding this comment.
I admit that this is not easy to spot. However I hesitate to add the specific states into the comments because I'm afraid that it might get out of sync. In this blog post I wrote about which state are not reachable. TL;DR: switching to in_field_layout and in_field_braces from in_section is only done in the parser.
Do you think I should detail this in the comments?
There was a problem hiding this comment.
Looking at Distribution.Fields.Lexer, I see both setStartCode in_field_layout and setStartCode in_field_braces, so it can switch to these states on its own. Am I missing something?
There was a problem hiding this comment.
Correct, bol_field_layout and in_field_layout can switch to each other, but without something that switches from in_section to in_field_layout the lexer would reach neither bol_field_layout nor in_field_layout states.
There was a problem hiding this comment.
OK, then I'd suggest to say exactly that, because the current wording is confusing. All states are reachable from the lexer itself, it's just that certain transitions of state are not.
There was a problem hiding this comment.
I can surely reword it, but
All states are reachable from the lexer itself, it's just that certain transitions of state are not.
is incorrect.
Here's an illustration stolen from my comment-preserving cabal parser article. The blue transitions are done by the field parser, while the red transitions are done by the lexer. You can see that without the field parser, you don't reach two whole classes of states, namely {in,bol}_field_layout and {in,bol}_field_braces.

There was a problem hiding this comment.
Thanks for the correction. I suggest to expand the comment (my confusion is a sure sign that other readers might have the same misunderstanding), maybe even with some ASCII art, but up to you.
There was a problem hiding this comment.
Indeed, I think adding a ASCII flow chart in the comments would help people :)
8b5a459 to
9559b20
Compare
This lays the foundation for Cabal-exactprint to consume user comments.
The parser of the envelope format ("field parser") now annotates each of
the parsed fields with its preceding and succeeding comments, along with
the existing source location annotation 'Position'.
This change is orthogonal to the final chosen exactprint implementation,
or the algebra we use to modify existing fields and/or generate new
fields. Instead, it merely makes the user comments available to any
consumer that reads cabal fields, the envelope format.
readFields* functions now have their counterparts that parses with
comments, named readFieldsWithComments*.
9559b20 to
3b4eb5a
Compare
This is the first part of the exact print parser. In this PR I changed the lexer so instead of dropping the comments it emits them to the parser which is further stored in
GenericPackageDescription.Please let me know your thoughts!
Checklist below:
This PR modifies behaviour or interface
Include the following checklist in your PR:
significance: significantin the changelog file.