xref: /aosp_15_r20/external/tensorflow/tensorflow/c/experimental/ops/gen/common/source_code.cc (revision b6fb3261f9314811a0f4371741dbb8839866f948)
1 /* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 #include "tensorflow/c/experimental/ops/gen/common/source_code.h"
16 
17 #include "absl/strings/match.h"
18 #include "tensorflow/core/lib/strings/str_util.h"
19 #include "tensorflow/core/platform/logging.h"
20 
21 namespace tensorflow {
22 namespace generator {
23 
Render() const24 string SourceCode::Render() const {
25   string code;
26   for (const Line& line : lines_) {
27     absl::StrAppend(&code, string(line.indent * spaces_per_indent_, ' '),
28                     line.text, "\n");
29   }
30   return code;
31 }
32 
AddLineWithIndent(const string & line)33 void SourceCode::AddLineWithIndent(const string& line) {
34   ValidateAndAddLine(current_indent_, line);
35 }
36 
AddLineWithoutIndent(const string & line)37 void SourceCode::AddLineWithoutIndent(const string& line) {
38   ValidateAndAddLine(0, line);
39 }
40 
AddBlankLine()41 void SourceCode::AddBlankLine() { ValidateAndAddLine(0, ""); }
42 
IncreaseIndent()43 void SourceCode::IncreaseIndent() { current_indent_++; }
44 
DecreaseIndent()45 void SourceCode::DecreaseIndent() { current_indent_--; }
46 
ValidateAndAddLine(int indent,const string & raw_line)47 void SourceCode::ValidateAndAddLine(int indent, const string& raw_line) {
48   StringPiece line(raw_line);
49   bool had_trailing_newline = str_util::ConsumeSuffix(&line, "\n");
50 
51   if (absl::StrContains(line, '\n')) {
52     LOG(ERROR) << "Attempt to add multiple lines; bad formatting is likely.";
53   } else if (had_trailing_newline) {
54     LOG(WARNING) << "Superfluous trailing newline in '" << line << "'";
55   }
56   lines_.push_back({indent, string(absl::StripTrailingAsciiWhitespace(line))});
57 }
58 
59 }  // namespace generator
60 }  // namespace tensorflow
61