Class used to generate the code for proto text functions. One of these should be created for each FileDescriptor whose code should be generated. This class has a notion of the current output Section. The Print, Nested, and Unnest functions apply their operations to the current output section, which can be toggled with SetOutput. Note that on the generated code, various pieces are not optimized
| 57 | // example: map input and output, Cord input and output, comparisons against |
| 58 | // the field names (it's a loop over all names), and tracking of has_seen. |
| 59 | class Generator { |
| 60 | public: |
| 61 | explicit Generator(const string& tf_header_prefix) |
| 62 | : tf_header_prefix_(tf_header_prefix), |
| 63 | header_(&code_.header), |
| 64 | header_impl_(&code_.header_impl), |
| 65 | cc_(&code_.cc) {} |
| 66 | |
| 67 | void Generate(const FileDescriptor& fd); |
| 68 | |
| 69 | // The generated code; valid after Generate has been called. |
| 70 | ProtoTextFunctionCode code() const { return code_; } |
| 71 | |
| 72 | private: |
| 73 | struct Section { |
| 74 | explicit Section(string* str) : str(str) {} |
| 75 | string* str; |
| 76 | string indent; |
| 77 | }; |
| 78 | |
| 79 | // Switches the currently active section to <section>. |
| 80 | Generator& SetOutput(Section* section) { |
| 81 | cur_ = section; |
| 82 | return *this; |
| 83 | } |
| 84 | |
| 85 | // Increases indent level. Returns <*this>, to allow chaining. |
| 86 | Generator& Nest() { |
| 87 | StrAppend(&cur_->indent, " "); |
| 88 | return *this; |
| 89 | } |
| 90 | |
| 91 | // Decreases indent level. Returns <*this>, to allow chaining. |
| 92 | Generator& Unnest() { |
| 93 | cur_->indent = cur_->indent.substr(0, cur_->indent.size() - 2); |
| 94 | return *this; |
| 95 | } |
| 96 | |
| 97 | // Appends the concatenated args, with a trailing newline. Returns <*this>, to |
| 98 | // allow chaining. |
| 99 | template <typename... Args> |
| 100 | Generator& Print(Args... args) { |
| 101 | StrAppend(cur_->str, cur_->indent, args..., "\n"); |
| 102 | return *this; |
| 103 | } |
| 104 | |
| 105 | // Appends the print code for a single field's value. |
| 106 | // If <omit_default> is true, then the emitted code will not print zero-valued |
| 107 | // values. |
| 108 | // <field_expr> is code that when emitted yields the field's value. |
| 109 | void AppendFieldValueAppend(const FieldDescriptor& field, |
| 110 | const bool omit_default, |
| 111 | const string& field_expr); |
| 112 | |
| 113 | // Appends the print code for as single field. |
| 114 | void AppendFieldAppend(const FieldDescriptor& field); |
| 115 | |
| 116 | // Appends the print code for a message. May change which section is currently |