We could start by stealing some of the Go heuristics, which definitely have some shortcomings but work well enough for common cases in practice:
A CommentGroup represents a sequence of comments with no other tokens and no empty lines between.
A comment group g is associated with a node n if:
- g starts on the same line as n ends
- g starts on the line immediately following n, and there is at least one empty line after g and before the next node
- g starts before n and is not associated to the node before n via the previous rules
[It] tries to associate a comment group to the "largest" node possible: For instance, if the comment is a line comment trailing an assignment, the comment is associated with the entire assignment rather than just the last operand in the assignment.
We could start by stealing some of the Go heuristics, which definitely have some shortcomings but work well enough for common cases in practice: