From b424c0628bf6852823def7be57629c130af80ebc Mon Sep 17 00:00:00 2001 From: Nitish Date: Thu, 1 Aug 2024 19:44:03 +0530 Subject: [PATCH 1/6] [P4fmt]: attach comments Signed-off-by: Nitish --- backends/p4fmt/CMakeLists.txt | 2 + backends/p4fmt/attach.cpp | 81 +++++++++++++++++++++++++++++++++++ backends/p4fmt/attach.h | 49 +++++++++++++++++++++ backends/p4fmt/p4fmt.cpp | 14 ++++++ lib/source_file.cpp | 9 ++++ lib/source_file.h | 11 ++++- 6 files changed, 165 insertions(+), 1 deletion(-) create mode 100644 backends/p4fmt/attach.cpp create mode 100644 backends/p4fmt/attach.h mode change 100644 => 100755 lib/source_file.h diff --git a/backends/p4fmt/CMakeLists.txt b/backends/p4fmt/CMakeLists.txt index 4668e3da899..269a6ded55d 100644 --- a/backends/p4fmt/CMakeLists.txt +++ b/backends/p4fmt/CMakeLists.txt @@ -3,6 +3,7 @@ set(FMT_SRCS options.cpp main.cpp p4formatter.cpp + attach.cpp ) set(REFCHECK_SRCS @@ -10,6 +11,7 @@ set(REFCHECK_SRCS options.cpp p4fmt.cpp p4formatter.cpp + attach.cpp ) # p4fmt diff --git a/backends/p4fmt/attach.cpp b/backends/p4fmt/attach.cpp new file mode 100644 index 00000000000..307e6cbf918 --- /dev/null +++ b/backends/p4fmt/attach.cpp @@ -0,0 +1,81 @@ +#include "backends/p4fmt/attach.h" + +#include "frontends/common/parser_options.h" +#include "lib/source_file.h" + +namespace P4::P4Fmt { + +Attach::~Attach() = default; + +void Attach::addPrefixComments(NodeId node, const Util::Comment *prefix) { + commentsMap[node].prefix.push_back(prefix); +} + +void Attach::addSuffixComments(NodeId node, const Util::Comment *suffix) { + commentsMap[node].suffix.push_back(suffix); +} + +bool Attach::isSystemFile(const std::filesystem::path &file) { + const std::filesystem::path p4include(p4includePath); + return file.parent_path() == p4include; +} + +const Attach::CommentsMap &Attach::getCommentsMap() const { return commentsMap; } + +const IR::Node *Attach::attachCommentsToNode(IR::Node *node, TraversalType ttype) { + if (node == nullptr || !node->srcInfo.isValid() || clist.empty()) { + return node; + } + std::filesystem::path sourceFile(node->srcInfo.getSourceFile().c_str()); + if (isSystemFile(sourceFile)) { + // Skip attachment for system files + return node; + } + + const auto nodeStart = node->srcInfo.getStart(); + + auto itr = clist.begin(); + while (itr != clist.end()) { + const Util::Comment *comment = *itr; + const auto &commentEnd = comment->getEndPosition(); + + bool shouldRemove = false; + + switch (ttype) { + { + case TraversalType::Preorder: + if (commentEnd.getLineNumber() < nodeStart.getLineNumber()) { + addPrefixComments(node->id, comment); + shouldRemove = true; + } + break; + } + + { + case TraversalType::Postorder: + if (commentEnd.getLineNumber() == nodeStart.getLineNumber()) { + addSuffixComments(node->id, comment); + shouldRemove = true; + } + break; + } + default: + ::P4::error(ErrorType::ERR_INVALID, "traversal type unknown/unsupported."); + return node; + } + + itr = shouldRemove ? clist.erase(itr) : std::next(itr); + } + + return node; +} + +const IR::Node *Attach::preorder(IR::Node *node) { + return attachCommentsToNode(node, TraversalType::Preorder); +} + +const IR::Node *Attach::postorder(IR::Node *node) { + return attachCommentsToNode(node, TraversalType::Postorder); +} + +} // namespace P4::P4Fmt diff --git a/backends/p4fmt/attach.h b/backends/p4fmt/attach.h new file mode 100644 index 00000000000..1446cfb2f37 --- /dev/null +++ b/backends/p4fmt/attach.h @@ -0,0 +1,49 @@ +#ifndef BACKENDS_P4FMT_ATTACH_H_ +#define BACKENDS_P4FMT_ATTACH_H_ + +#include +#include +#include + +#include "backends/p4fmt/p4fmt.h" +#include "ir/ir.h" +#include "ir/visitor.h" +#include "lib/source_file.h" + +namespace P4::P4Fmt { + +class Attach : public Transform { + public: + using NodeId = int; + struct Comments { + std::vector prefix; + std::vector suffix; + }; + using CommentsMap = std::unordered_map; + enum class TraversalType { Preorder, Postorder }; + + explicit Attach(const std::unordered_set &clist) : clist(clist){}; + ~Attach() override; + + const IR::Node *attachCommentsToNode(IR::Node *, TraversalType); + + using Transform::postorder; + using Transform::preorder; + + const IR::Node *preorder(IR::Node *node) override; + const IR::Node *postorder(IR::Node *node) override; + + static bool isSystemFile(const std::filesystem::path &file); + + void addPrefixComments(NodeId, const Util::Comment *); + void addSuffixComments(NodeId, const Util::Comment *); + const CommentsMap &getCommentsMap() const; + + private: + std::unordered_set clist; + CommentsMap commentsMap; +}; + +} // namespace P4::P4Fmt + +#endif /* BACKENDS_P4FMT_ATTACH_H_ */ diff --git a/backends/p4fmt/p4fmt.cpp b/backends/p4fmt/p4fmt.cpp index 72aa602181e..f8eff132a10 100644 --- a/backends/p4fmt/p4fmt.cpp +++ b/backends/p4fmt/p4fmt.cpp @@ -1,5 +1,6 @@ #include "backends/p4fmt/p4fmt.h" +#include "backends/p4fmt/attach.h" #include "frontends/common/parseInput.h" #include "frontends/common/parser_options.h" #include "ir/ir.h" @@ -24,7 +25,20 @@ std::stringstream getFormattedOutput(std::filesystem::path inputFile) { return formattedOutput; } + std::unordered_set globalCommentsList; + // get the global list of comments + if (!program->objects.empty()) { + const auto *firstNode = program->objects.front(); + if (firstNode->srcInfo.isValid()) { + for (const auto *comment : firstNode->srcInfo.getAllFileComments()) { + globalCommentsList.insert(comment); + } + } + } + auto top4 = P4Fmt::P4Formatter(&formattedOutput); + auto attach = P4::P4Fmt::Attach(globalCommentsList); + program = program->apply(attach); // Print the program before running front end passes. program->apply(top4); diff --git a/lib/source_file.cpp b/lib/source_file.cpp index 85d3e38ba4a..e2cdc81b430 100644 --- a/lib/source_file.cpp +++ b/lib/source_file.cpp @@ -69,6 +69,13 @@ std::ostream &operator<<(std::ostream &os, const SourceInfo &info) { return os; } +const std::vector SourceInfo::getAllFileComments() const { + if (sources == nullptr) { + return {}; + } + return this->sources->getAllComments(); +} + ////////////////////////////////////////////////////////////////////////////////////////// InputSources::InputSources() : sealed(false) { @@ -83,6 +90,8 @@ void InputSources::addComment(SourceInfo srcInfo, bool singleLine, cstring body) comments.push_back(new Comment(srcInfo, singleLine, body)); } +const std::vector &InputSources::getAllComments() const { return comments; } + /// prevent further changes void InputSources::seal() { LOG4(toDebugString()); diff --git a/lib/source_file.h b/lib/source_file.h old mode 100644 new mode 100755 index 76927ee7c53..9e2f4a49a06 --- a/lib/source_file.h +++ b/lib/source_file.h @@ -110,6 +110,7 @@ class SourcePosition final { }; class InputSources; +class Comment; /** Information about the source position of a language element - @@ -188,6 +189,8 @@ class SourceInfo final { const SourcePosition &getEnd() const { return this->end; } + [[nodiscard]] const std::vector getAllFileComments() const; + /** True if this comes 'before' this source position. 'invalid' source positions come first. @@ -261,6 +264,10 @@ class Comment final : IHasDbPrint { out << body; if (!singleLine) out << "*/"; } + + // Retrieve the source position associated with this comment. + [[nodiscard]] const SourcePosition &getStartPosition() const { return srcInfo.getStart(); } + [[nodiscard]] const SourcePosition &getEndPosition() const { return srcInfo.getEnd(); } }; /** @@ -280,7 +287,6 @@ class InputSources final { public: InputSources(); - std::string_view getLine(unsigned lineNumber) const; /// Original source line that produced the line with the specified number SourceFileLine getSourceLine(unsigned line) const; @@ -312,6 +318,9 @@ class InputSources final { cstring toDebugString() const; void addComment(SourceInfo srcInfo, bool singleLine, cstring body); + // Returns a list of all the comments found in the file, stored as a part of `InputSources` + const std::vector &getAllComments() const; + private: /// Append this text to the last line; must not contain newlines void appendToLastLine(std::string_view text); From e9f53dc63cce64f1b41fcdc8767e57244f0a1e56 Mon Sep 17 00:00:00 2001 From: Nitish Date: Mon, 26 Aug 2024 14:09:23 +0530 Subject: [PATCH 2/6] fix: resolve issue with modifying container during iteration Signed-off-by: Nitish --- backends/p4fmt/attach.cpp | 47 ++++++++++++++++++--------------------- backends/p4fmt/attach.h | 5 +++-- backends/p4fmt/p4fmt.cpp | 12 ++++++---- 3 files changed, 33 insertions(+), 31 deletions(-) diff --git a/backends/p4fmt/attach.cpp b/backends/p4fmt/attach.cpp index 307e6cbf918..0c4da9b9dd3 100644 --- a/backends/p4fmt/attach.cpp +++ b/backends/p4fmt/attach.cpp @@ -23,9 +23,10 @@ bool Attach::isSystemFile(const std::filesystem::path &file) { const Attach::CommentsMap &Attach::getCommentsMap() const { return commentsMap; } const IR::Node *Attach::attachCommentsToNode(IR::Node *node, TraversalType ttype) { - if (node == nullptr || !node->srcInfo.isValid() || clist.empty()) { + if (node == nullptr || !node->srcInfo.isValid() || processedComments.empty()) { return node; } + std::filesystem::path sourceFile(node->srcInfo.getSourceFile().c_str()); if (isSystemFile(sourceFile)) { // Skip attachment for system files @@ -34,37 +35,33 @@ const IR::Node *Attach::attachCommentsToNode(IR::Node *node, TraversalType ttype const auto nodeStart = node->srcInfo.getStart(); - auto itr = clist.begin(); - while (itr != clist.end()) { - const Util::Comment *comment = *itr; - const auto &commentEnd = comment->getEndPosition(); + for (auto &[comment, isVisited] : processedComments) { + // Skip if already attached + if (isVisited) { + continue; + } - bool shouldRemove = false; + const auto &commentEnd = comment->getEndPosition(); switch (ttype) { - { - case TraversalType::Preorder: - if (commentEnd.getLineNumber() < nodeStart.getLineNumber()) { - addPrefixComments(node->id, comment); - shouldRemove = true; - } - break; - } - - { - case TraversalType::Postorder: - if (commentEnd.getLineNumber() == nodeStart.getLineNumber()) { - addSuffixComments(node->id, comment); - shouldRemove = true; - } - break; - } + case TraversalType::Preorder: + if (commentEnd.getLineNumber() == nodeStart.getLineNumber() - 1) { + addPrefixComments(node->id, comment); + isVisited = true; // Mark the comment as attached + } + break; + + case TraversalType::Postorder: + if (commentEnd.getLineNumber() == nodeStart.getLineNumber()) { + addSuffixComments(node->id, comment); + isVisited = true; + } + break; + default: ::P4::error(ErrorType::ERR_INVALID, "traversal type unknown/unsupported."); return node; } - - itr = shouldRemove ? clist.erase(itr) : std::next(itr); } return node; diff --git a/backends/p4fmt/attach.h b/backends/p4fmt/attach.h index 1446cfb2f37..f01f8458f68 100644 --- a/backends/p4fmt/attach.h +++ b/backends/p4fmt/attach.h @@ -22,7 +22,8 @@ class Attach : public Transform { using CommentsMap = std::unordered_map; enum class TraversalType { Preorder, Postorder }; - explicit Attach(const std::unordered_set &clist) : clist(clist){}; + explicit Attach(const std::unordered_map &processedComments) + : processedComments(processedComments){}; ~Attach() override; const IR::Node *attachCommentsToNode(IR::Node *, TraversalType); @@ -40,7 +41,7 @@ class Attach : public Transform { const CommentsMap &getCommentsMap() const; private: - std::unordered_set clist; + std::unordered_map processedComments; CommentsMap commentsMap; }; diff --git a/backends/p4fmt/p4fmt.cpp b/backends/p4fmt/p4fmt.cpp index f8eff132a10..26608606ae2 100644 --- a/backends/p4fmt/p4fmt.cpp +++ b/backends/p4fmt/p4fmt.cpp @@ -25,19 +25,23 @@ std::stringstream getFormattedOutput(std::filesystem::path inputFile) { return formattedOutput; } - std::unordered_set globalCommentsList; - // get the global list of comments + std::unordered_map globalCommentsMap; + + // Initialize the global comments map from the list of comments in the program. + // The map associates each comment with a boolean value that tracks whether the comment + // has been processed for attachment to IR nodes. Initially, all comments are set to 'false', + // indicating that they have not yet been processed. if (!program->objects.empty()) { const auto *firstNode = program->objects.front(); if (firstNode->srcInfo.isValid()) { for (const auto *comment : firstNode->srcInfo.getAllFileComments()) { - globalCommentsList.insert(comment); + globalCommentsMap[comment] = false; // Initialize all comments as not visited } } } auto top4 = P4Fmt::P4Formatter(&formattedOutput); - auto attach = P4::P4Fmt::Attach(globalCommentsList); + auto attach = P4::P4Fmt::Attach(globalCommentsMap); program = program->apply(attach); // Print the program before running front end passes. program->apply(top4); From 0dfc44a4f4a3294ea621b13865471ba93ff09048 Mon Sep 17 00:00:00 2001 From: Nitish Date: Mon, 26 Aug 2024 15:28:57 +0530 Subject: [PATCH 3/6] refactor: rename variables, remove unused headers Signed-off-by: Nitish --- backends/p4fmt/attach.cpp | 8 ++++---- backends/p4fmt/attach.h | 9 +++++---- backends/p4fmt/p4fmt.cpp | 6 ++---- 3 files changed, 11 insertions(+), 12 deletions(-) diff --git a/backends/p4fmt/attach.cpp b/backends/p4fmt/attach.cpp index 0c4da9b9dd3..c347402ac1f 100644 --- a/backends/p4fmt/attach.cpp +++ b/backends/p4fmt/attach.cpp @@ -35,9 +35,9 @@ const IR::Node *Attach::attachCommentsToNode(IR::Node *node, TraversalType ttype const auto nodeStart = node->srcInfo.getStart(); - for (auto &[comment, isVisited] : processedComments) { + for (auto &[comment, isAttached] : processedComments) { // Skip if already attached - if (isVisited) { + if (isAttached) { continue; } @@ -47,14 +47,14 @@ const IR::Node *Attach::attachCommentsToNode(IR::Node *node, TraversalType ttype case TraversalType::Preorder: if (commentEnd.getLineNumber() == nodeStart.getLineNumber() - 1) { addPrefixComments(node->id, comment); - isVisited = true; // Mark the comment as attached + isAttached = true; // Mark the comment as attached } break; case TraversalType::Postorder: if (commentEnd.getLineNumber() == nodeStart.getLineNumber()) { addSuffixComments(node->id, comment); - isVisited = true; + isAttached = true; } break; diff --git a/backends/p4fmt/attach.h b/backends/p4fmt/attach.h index f01f8458f68..64e8ac98f1f 100644 --- a/backends/p4fmt/attach.h +++ b/backends/p4fmt/attach.h @@ -1,12 +1,10 @@ #ifndef BACKENDS_P4FMT_ATTACH_H_ #define BACKENDS_P4FMT_ATTACH_H_ +#include #include -#include #include -#include "backends/p4fmt/p4fmt.h" -#include "ir/ir.h" #include "ir/visitor.h" #include "lib/source_file.h" @@ -22,7 +20,7 @@ class Attach : public Transform { using CommentsMap = std::unordered_map; enum class TraversalType { Preorder, Postorder }; - explicit Attach(const std::unordered_map &processedComments) + explicit Attach(const std::unordered_map &processedComments) : processedComments(processedComments){}; ~Attach() override; @@ -41,7 +39,10 @@ class Attach : public Transform { const CommentsMap &getCommentsMap() const; private: + // This Hashmap tracks each comment’s attachment status to IR nodes. Initially, all comments are + // set to 'false'. std::unordered_map processedComments; + CommentsMap commentsMap; }; diff --git a/backends/p4fmt/p4fmt.cpp b/backends/p4fmt/p4fmt.cpp index 26608606ae2..8127d3c8e08 100644 --- a/backends/p4fmt/p4fmt.cpp +++ b/backends/p4fmt/p4fmt.cpp @@ -28,14 +28,12 @@ std::stringstream getFormattedOutput(std::filesystem::path inputFile) { std::unordered_map globalCommentsMap; // Initialize the global comments map from the list of comments in the program. - // The map associates each comment with a boolean value that tracks whether the comment - // has been processed for attachment to IR nodes. Initially, all comments are set to 'false', - // indicating that they have not yet been processed. if (!program->objects.empty()) { const auto *firstNode = program->objects.front(); if (firstNode->srcInfo.isValid()) { for (const auto *comment : firstNode->srcInfo.getAllFileComments()) { - globalCommentsMap[comment] = false; // Initialize all comments as not visited + globalCommentsMap[comment] = + false; // Initialize all comments as not yet attached to nodes } } } From 59ff8479cf0926bceee176d2498ee0e6de5ae628 Mon Sep 17 00:00:00 2001 From: Nitish Date: Tue, 27 Aug 2024 18:28:31 +0530 Subject: [PATCH 4/6] [WIP]: comment formatting for structs and typedefs Signed-off-by: Nitish --- backends/p4fmt/p4fmt.cpp | 2 +- backends/p4fmt/p4formatter.cpp | 33 ++++++++++++++++++++++++++++++--- backends/p4fmt/p4formatter.h | 15 ++++++++++++--- 3 files changed, 43 insertions(+), 7 deletions(-) diff --git a/backends/p4fmt/p4fmt.cpp b/backends/p4fmt/p4fmt.cpp index 8127d3c8e08..22a3ce5053b 100644 --- a/backends/p4fmt/p4fmt.cpp +++ b/backends/p4fmt/p4fmt.cpp @@ -38,10 +38,10 @@ std::stringstream getFormattedOutput(std::filesystem::path inputFile) { } } - auto top4 = P4Fmt::P4Formatter(&formattedOutput); auto attach = P4::P4Fmt::Attach(globalCommentsMap); program = program->apply(attach); // Print the program before running front end passes. + auto top4 = P4Fmt::P4Formatter(&formattedOutput, attach.getCommentsMap()); program->apply(top4); if (::P4::errorCount() > 0) { diff --git a/backends/p4fmt/p4formatter.cpp b/backends/p4fmt/p4formatter.cpp index 73d8f4ee416..3cc05db4caa 100644 --- a/backends/p4fmt/p4formatter.cpp +++ b/backends/p4fmt/p4formatter.cpp @@ -1,10 +1,8 @@ #include "p4formatter.h" -#include #include #include -#include "frontends/common/options.h" #include "frontends/p4/fromv1.0/v1model.h" #include "frontends/parsers/p4/p4parser.hpp" #include "ir/dump.h" @@ -43,6 +41,18 @@ std::filesystem::path P4Formatter::ifSystemFile(const IR::Node *node) { return {}; } +std::pair P4Formatter::extractNodeComments(int nodeId) { + auto commsIt = comMap.find(nodeId); + if (commsIt != comMap.end()) { + const Attach::Comments &comms = commsIt->second; + cstring prefixComm = comms.prefix.empty() ? cstring("") : comms.prefix.front()->toString(); + cstring suffixComm = comms.suffix.empty() ? cstring("") : comms.suffix.front()->toString(); + return std::make_pair(prefixComm, suffixComm); + } + // Return empty strings if node ID not found + return {cstring(""), cstring("")}; +} + bool P4Formatter::preorder(const IR::Node *node) { P4C_UNIMPLEMENTED("Unhandled IR node type: ", node->node_type_name()); return false; @@ -174,6 +184,11 @@ bool P4Formatter::preorder(const IR::Argument *arg) { } bool P4Formatter::preorder(const IR::Type_Typedef *t) { + auto [prefixc, suffixc] = extractNodeComments(t->id); + if (*prefixc != 0) { + builder.append(prefixc); + builder.append("\n"); + } if (!t->annotations->annotations.empty()) { visit(t->annotations); builder.spc(); @@ -386,6 +401,10 @@ bool P4Formatter::preorder(const IR::Type_Package *package) { } bool P4Formatter::process(const IR::Type_StructLike *t, const char *name) { + auto [prefixc, suffixc] = extractNodeComments(t->id); + + builder.append(prefixc); + builder.append("\n"); if (isDeclaration) { builder.emitIndent(); if (!t->annotations->annotations.empty()) { @@ -413,6 +432,13 @@ bool P4Formatter::process(const IR::Type_StructLike *t, const char *name) { } for (auto f : t->fields) { + auto [fieldPrefixc, fieldSuffixc] = extractNodeComments(f->id); + if (*fieldPrefixc != 0) { + builder.emitIndent(); + builder.append(fieldPrefixc); + builder.newline(); + } + if (f->annotations->size() > 0) { builder.emitIndent(); if (!f->annotations->annotations.empty()) { @@ -1456,7 +1482,8 @@ bool P4Formatter::preorder(const IR::Path *p) { std::string toP4(const IR::INode *node) { std::stringstream stream; - P4Fmt::P4Formatter toP4(&stream); + Attach::CommentsMap comMap; + P4Fmt::P4Formatter toP4(&stream, comMap); node->getNode()->apply(toP4); return stream.str(); } diff --git a/backends/p4fmt/p4formatter.h b/backends/p4fmt/p4formatter.h index 8a0844d89fc..c9aff4ae5fe 100644 --- a/backends/p4fmt/p4formatter.h +++ b/backends/p4fmt/p4formatter.h @@ -1,6 +1,9 @@ #ifndef BACKENDS_P4FMT_P4FORMATTER_H_ #define BACKENDS_P4FMT_P4FORMATTER_H_ +#include + +#include "backends/p4fmt/attach.h" #include "frontends/common/resolveReferences/resolveReferences.h" #include "ir/ir.h" #include "ir/visitor.h" @@ -123,13 +126,15 @@ class P4Formatter : public Inspector, ::P4::ResolutionContext { visitDagOnce = false; setName("P4Formatter"); } - explicit P4Formatter(std::ostream *outStream, cstring mainFile = nullptr) + explicit P4Formatter(std::ostream *outStream, Attach::Attach::CommentsMap comMap, + cstring mainFile = nullptr) : expressionPrecedence(DBPrint::Prec_Low), isDeclaration(true), withinArgument(false), builder(*new Util::SourceCodeBuilder()), outStream(outStream), - mainFile(mainFile) { + mainFile(mainFile), + comMap(std::move(comMap)) { visitDagOnce = false; setName("P4Formatter"); } @@ -145,10 +150,11 @@ class P4Formatter : public Inspector, ::P4::ResolutionContext { setName("P4Formatter"); } + std::pair extractNodeComments(int nodeId); void setnoIncludesArg(bool condition) { noIncludes = condition; } void setListTerm(const char *start, const char *end) { - listTerminators.push_back(ListPrint(start, end)); + listTerminators.emplace_back(start, end); } Visitor::profile_t init_apply(const IR::Node *node) override; void end_apply(const IR::Node *node) override; @@ -290,6 +296,9 @@ class P4Formatter : public Inspector, ::P4::ResolutionContext { // in case it is accidentally called on a V1Program bool preorder(const IR::V1Program *) override { return false; } + + private: + Attach::Attach::CommentsMap comMap; }; std::string toP4(const IR::INode *node); From e40857586a3178c030f0c951facfb4b5cc2359c0 Mon Sep 17 00:00:00 2001 From: Nitish Date: Tue, 27 Aug 2024 19:45:51 +0530 Subject: [PATCH 5/6] add support for control blocks, property and action blocks Signed-off-by: Nitish --- backends/p4fmt/p4formatter.cpp | 25 ++++++++++++++++++++++++- backends/p4fmt/p4formatter.h | 2 -- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/backends/p4fmt/p4formatter.cpp b/backends/p4fmt/p4formatter.cpp index 3cc05db4caa..2ba47ab0b4e 100644 --- a/backends/p4fmt/p4formatter.cpp +++ b/backends/p4fmt/p4formatter.cpp @@ -45,6 +45,7 @@ std::pair P4Formatter::extractNodeComments(int nodeId) { auto commsIt = comMap.find(nodeId); if (commsIt != comMap.end()) { const Attach::Comments &comms = commsIt->second; + // Since we have only one prefix & suffix comment per node for now cstring prefixComm = comms.prefix.empty() ? cstring("") : comms.prefix.front()->toString(); cstring suffixComm = comms.suffix.empty() ? cstring("") : comms.suffix.front()->toString(); return std::make_pair(prefixComm, suffixComm); @@ -479,6 +480,11 @@ bool P4Formatter::preorder(const IR::Type_Control *t) { visit(t->annotations); builder.spc(); } + auto [prefixc, suffixc] = extractNodeComments(t->id); + if (*prefixc != 0) { + builder.append(prefixc); + builder.append("\n"); + } builder.append("control "); builder.append(t->name); visit(t->typeParameters); @@ -1253,6 +1259,12 @@ bool P4Formatter::preorder(const IR::Parameter *p) { } bool P4Formatter::preorder(const IR::P4Control *c) { + auto [prefixc, suffixc] = extractNodeComments(c->id); + if (*prefixc != 0) { + builder.append(prefixc); + builder.append("\n"); + builder.emitIndent(); + } bool decl = isDeclaration; isDeclaration = false; visit(c->type); @@ -1265,7 +1277,6 @@ bool P4Formatter::preorder(const IR::P4Control *c) { visit(s); builder.newline(); } - builder.emitIndent(); builder.append("apply "); visit(c->body); @@ -1282,6 +1293,12 @@ bool P4Formatter::preorder(const IR::ParameterList *p) { } bool P4Formatter::preorder(const IR::P4Action *c) { + auto [prefixc, suffixc] = extractNodeComments(c->id); + if (*prefixc != 0) { + builder.append(prefixc); + builder.append("\n"); + builder.emitIndent(); + } if (!c->annotations->annotations.empty()) { visit(c->annotations); builder.spc(); @@ -1404,6 +1421,12 @@ bool P4Formatter::preorder(const IR::Key *v) { } bool P4Formatter::preorder(const IR::Property *p) { + auto [prefixc, suffixc] = extractNodeComments(p->id); + if (*prefixc != 0) { + builder.append(prefixc); + builder.append("\n"); + builder.emitIndent(); + } if (!p->annotations->annotations.empty()) { visit(p->annotations); builder.spc(); diff --git a/backends/p4fmt/p4formatter.h b/backends/p4fmt/p4formatter.h index c9aff4ae5fe..b90dc074bf3 100644 --- a/backends/p4fmt/p4formatter.h +++ b/backends/p4fmt/p4formatter.h @@ -1,8 +1,6 @@ #ifndef BACKENDS_P4FMT_P4FORMATTER_H_ #define BACKENDS_P4FMT_P4FORMATTER_H_ -#include - #include "backends/p4fmt/attach.h" #include "frontends/common/resolveReferences/resolveReferences.h" #include "ir/ir.h" From ea864a741e3f2d6314828a436b16f83566cbf5a3 Mon Sep 17 00:00:00 2001 From: Nitish Date: Wed, 28 Aug 2024 20:44:51 +0530 Subject: [PATCH 6/6] update ref file Signed-off-by: Nitish --- backends/p4fmt/ref.p4 | 75 +++++++++++++++++++++++++++++++++++++++---- 1 file changed, 68 insertions(+), 7 deletions(-) diff --git a/backends/p4fmt/ref.p4 b/backends/p4fmt/ref.p4 index 7d574b9d203..c992bce6b83 100644 --- a/backends/p4fmt/ref.p4 +++ b/backends/p4fmt/ref.p4 @@ -1,20 +1,81 @@ /* -*- P4_16 -*- */ +#include +#include const bit<16> TYPE_IPV4 = 0x800; -typedef bit<9> egressSpec_t; -typedef bit<48> macAddr_t; +typedef bit<9> egressSpec_t; //typedef egress +typedef bit<48> macAddr_t; // typedef macaddr +// before ipv4addr typedef bit<32> ip4Addr_t; - header ethernet_t { macAddr_t dstAddr; + // TypeName: srcAddr + macAddr_t srcAddr; + bit<16> etherType; // inline Type_Bits +} - // comm1 - macAddr_t srcAddr; // comm2 +header ipv4_t { + bit<4> version; + bit<4> ihl; + bit<8> diffserv; + bit<16> totalLen; + bit<16> identification; + bit<3> flags; // type comment + bit<13> fragOffset; + bit<8> ttl; + bit<8> protocol; + bit<16> hdrChecksum; + ip4Addr_t srcAddr; + ip4Addr_t dstAddr; +} - bit<16> etherType; +struct metadata { + /* empty */ } +// struct comment struct headers { - ethernet_t ethernet; + // struct field comment + ethernet_t ethernet; + ipv4_t ipv4; +} + +// free floating + +// control block checksum +control MyVerifyChecksum(inout headers hdr, inout metadata meta) { + apply { } +} + +// control block ingress +control MyIngress( /*argument comment*/ inout headers hdr, + inout metadata meta, + inout standard_metadata_t standard_metadata) { + // function call + action drop() { + mark_to_drop(standard_metadata); + } + + action ipv4_forward(macAddr_t dstAddr, egressSpec_t port) { + } + + table ipv4_lpm { + key = { + hdr.ipv4.dstAddr: lpm; // match on dest ipv4 + } + // action block + actions = { + ipv4_forward; + drop; + NoAction; + } + size = 1024; // table size + default_action = NoAction(); + } + + // apply fn call + apply { + ipv4_lpm.apply(); // apply table + } }