MLIR  16.0.0git
IndentedOstream.cpp
Go to the documentation of this file.
1 //===- IndentedOstream.cpp - raw ostream wrapper to indent ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // raw_ostream subclass that keeps track of indentation for textual output
10 // where indentation helps readability.
11 //
12 //===----------------------------------------------------------------------===//
13 
15 
16 using namespace mlir;
17 
20  StringRef extraPrefix) {
21  StringRef output = str;
22  // Skip empty lines.
23  while (!output.empty()) {
24  auto split = output.split('\n');
25  size_t indent = split.first.find_first_not_of(" \t");
26  if (indent != StringRef::npos) {
27  // Set an initial value.
28  leadingWs = indent;
29  break;
30  }
31  output = split.second;
32  }
33  // Determine the maximum indent.
34  StringRef remaining = output;
35  while (!remaining.empty()) {
36  auto split = remaining.split('\n');
37  size_t indent = split.first.find_first_not_of(" \t");
38  if (indent != StringRef::npos)
39  leadingWs = std::min(leadingWs, static_cast<int>(indent));
40  remaining = split.second;
41  }
42  // Print, skipping the empty lines.
43  std::swap(currentExtraPrefix, extraPrefix);
44  *this << output;
45  std::swap(currentExtraPrefix, extraPrefix);
46  leadingWs = 0;
47  return *this;
48 }
49 
50 void mlir::raw_indented_ostream::write_impl(const char *ptr, size_t size) {
51  StringRef str(ptr, size);
52  // Print out indented.
53  auto print = [this](StringRef str) {
54  if (atStartOfLine)
55  os.indent(currentIndent) << currentExtraPrefix << str.substr(leadingWs);
56  else
57  os << str.substr(leadingWs);
58  };
59 
60  while (!str.empty()) {
61  size_t idx = str.find('\n');
62  if (idx == StringRef::npos) {
63  if (!str.substr(leadingWs).empty()) {
64  print(str);
65  atStartOfLine = false;
66  }
67  break;
68  }
69 
70  auto split =
71  std::make_pair(str.slice(0, idx), str.slice(idx + 1, StringRef::npos));
72  // Print empty new line without spaces if line only has spaces and no extra
73  // prefix is requested.
74  if (!split.first.ltrim().empty() || !currentExtraPrefix.empty())
75  print(split.first);
76  os << '\n';
77  atStartOfLine = true;
78  str = split.second;
79  }
80 }
static Value min(ImplicitLocOpBuilder &builder, Value value, Value bound)
static void print(spirv::VerCapExtAttr triple, DialectAsmPrinter &printer)
raw_ostream subclass that simplifies indention a sequence of code.
raw_indented_ostream & printReindented(StringRef str, StringRef extraPrefix="")
Prints a string re-indented to the current indent.
Include the generated interface declarations.