1 // Copyright 2020 The Tint Authors. 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 #ifndef SRC_DIAGNOSTIC_PRINTER_H_ 16 #define SRC_DIAGNOSTIC_PRINTER_H_ 17 18 #include <memory> 19 #include <sstream> 20 #include <string> 21 22 namespace tint { 23 namespace diag { 24 25 class List; 26 27 /// Color is an enumerator of colors used by Style. 28 enum class Color { 29 kDefault, 30 kBlack, 31 kRed, 32 kGreen, 33 kYellow, 34 kBlue, 35 kMagenta, 36 kCyan, 37 kWhite, 38 }; 39 40 /// Style describes how a diagnostic message should be printed. 41 struct Style { 42 /// The foreground text color 43 Color color = Color::kDefault; 44 /// If true the text will be displayed with a strong weight 45 bool bold = false; 46 }; 47 48 /// Printers are used to print formatted diagnostic messages to a terminal. 49 class Printer { 50 public: 51 /// @returns a diagnostic Printer 52 /// @param out the file to print to. 53 /// @param use_colors if true, the printer will use colors if `out` is a 54 /// terminal and supports them. 55 static std::unique_ptr<Printer> create(FILE* out, bool use_colors); 56 57 virtual ~Printer(); 58 59 /// writes the string str to the printer with the given style. 60 /// @param str the string to write to the printer 61 /// @param style the style used to print `str` 62 virtual void write(const std::string& str, const Style& style) = 0; 63 }; 64 65 /// StringPrinter is an implementation of Printer that writes to a std::string. 66 class StringPrinter : public Printer { 67 public: 68 StringPrinter(); 69 ~StringPrinter() override; 70 71 /// @returns the printed string. 72 std::string str() const; 73 74 void write(const std::string& str, const Style&) override; 75 76 private: 77 std::stringstream stream; 78 }; 79 80 } // namespace diag 81 } // namespace tint 82 83 #endif // SRC_DIAGNOSTIC_PRINTER_H_ 84