1 //===- WithColor.cpp ------------------------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "llvm/Support/WithColor.h" 11 #include "llvm/Support/CommandLine.h" 12 #include "llvm/Support/raw_ostream.h" 13 14 using namespace llvm; 15 16 static cl::opt<cl::boolOrDefault> 17 UseColor("color", 18 cl::desc("use colored syntax highlighting (default=autodetect)"), 19 cl::init(cl::BOU_UNSET)); 20 21 bool WithColor::colorsEnabled(raw_ostream &OS) { 22 if (UseColor == cl::BOU_UNSET) 23 return OS.has_colors(); 24 return UseColor == cl::BOU_TRUE; 25 } 26 27 WithColor::WithColor(raw_ostream &OS, HighlightColor Color) : OS(OS) { 28 // Detect color from terminal type unless the user passed the --color option. 29 if (colorsEnabled(OS)) { 30 switch (Color) { 31 case HighlightColor::Address: 32 OS.changeColor(raw_ostream::YELLOW); 33 break; 34 case HighlightColor::String: 35 OS.changeColor(raw_ostream::GREEN); 36 break; 37 case HighlightColor::Tag: 38 OS.changeColor(raw_ostream::BLUE); 39 break; 40 case HighlightColor::Attribute: 41 OS.changeColor(raw_ostream::CYAN); 42 break; 43 case HighlightColor::Enumerator: 44 OS.changeColor(raw_ostream::MAGENTA); 45 break; 46 case HighlightColor::Macro: 47 OS.changeColor(raw_ostream::RED); 48 break; 49 case HighlightColor::Error: 50 OS.changeColor(raw_ostream::RED, true); 51 break; 52 case HighlightColor::Warning: 53 OS.changeColor(raw_ostream::MAGENTA, true); 54 break; 55 case HighlightColor::Note: 56 OS.changeColor(raw_ostream::BLACK, true); 57 break; 58 } 59 } 60 } 61 62 raw_ostream &WithColor::error() { return error(errs()); } 63 64 raw_ostream &WithColor::warning() { return warning(errs()); } 65 66 raw_ostream &WithColor::note() { return note(errs()); } 67 68 raw_ostream &WithColor::error(raw_ostream &OS, StringRef Prefix) { 69 if (!Prefix.empty()) 70 OS << Prefix << ": "; 71 return WithColor(OS, HighlightColor::Error).get() << "error: "; 72 } 73 74 raw_ostream &WithColor::warning(raw_ostream &OS, StringRef Prefix) { 75 if (!Prefix.empty()) 76 OS << Prefix << ": "; 77 return WithColor(OS, HighlightColor::Warning).get() << "warning: "; 78 } 79 80 raw_ostream &WithColor::note(raw_ostream &OS, StringRef Prefix) { 81 if (!Prefix.empty()) 82 OS << Prefix << ": "; 83 return WithColor(OS, HighlightColor::Note).get() << "note: "; 84 } 85 86 WithColor::~WithColor() { 87 if (colorsEnabled(OS)) 88 OS.resetColor(); 89 } 90