p4c
p4c copied to clipboard
[p4fmt]: print comments
This PR is an initial attempt to print comments using p4fmt.It is not intended to be merged (atleast for now); it serves as a preliminary draft to initiate discussion and gather feedback from the community on potential approaches moving forward.
PR #1226 parsed and saved comments as part of the InputSources data structure for further use.
This PR outlines an approach where we take in that position information and associate it with the nodes while printing with toP4 . For this to work we need to modify each node type of toP4 to access comments related to that particular node(based solely on position info) and print accordingly.
(The PR demonstrates this wherein comments are printed related to Typedef nodes, It only associates the comments which are closest, things like comments on same line are not handled, multi-line comments are not handled, efficiency is not taken into account etc. This is just an intial attempt and code is very hack-ish).
Sample Input:
typedef bit<9> egressSpec_t;
// comm1
typedef bit<48> macAddr_t;
// comm2
typedef bit<32> ip4Addr_t;
header ethernet_t {
macAddr_t dstAddr;
// Comm3
macAddr_t srcAddr;
bit<16> etherType;
}
Sample Output:
typedef bit<9> egressSpec_t;
// comm1
typedef bit<48> macAddr_t;
// comm2
typedef bit<32> ip4Addr_t;
header ethernet_t {
macAddr_t dstAddr;
macAddr_t srcAddr;
bit<16> etherType;
}
A more sophisticated approach would be to include a separate common comments field in each node. By using the comment position information along with the nodes, we could traverse the AST nodes and associate the comments with the relevant nodes.
I would also recommend adding an option toP4 to toggle whether to add comments etc. This way you do not conflict with the current reference files in the compiler.
Thanks for the review :), I'll resolve those. Also, I'll go ahead with a separate transformative pass as discussed in the meeting for attaching nodes with comments, so that we can gradually build up on it & merge it upstream in smaller chunks.
@snapdgn Thanks for sharing the blog post Preserving comments when parsing and formatting code, I find it pretty informative. Especially the description on the algorithm for attaching comments to AST nodes, has made it much clearer to me how this could be done.
Thanks for all the reviews and comments, they've been incredibly helpful. :) I am convinced that this requires a major overhaul as the process of attaching comments needs to be addressed in a separate AST pass,regardless. I'll ensure to incorporate all the suggested changes in the rework.