// This file is part of AspectC++.
// Copyright (C) 1999-2015  The AspectC++ developer team.
//                                                                
// This program is free software;  you can redistribute it and/or 
// modify it under the terms of the GNU General Public License as 
// published by the Free Software Foundation; either version 2 of 
// the License, or (at your option) any later version.            
//                                                                
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of 
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the  
// GNU General Public License for more details.                   
//                                                                
// You should have received a copy of the GNU General Public      
// License along with this program; if not, write to the Free     
// Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, 
// MA  02111-1307  USA                                            

#include "ErrorStream.h"
#include <iostream>

namespace ACBase {

ErrorStream &ErrorStream::operator <<(ErrorSeverity sev) {
  m_currSeverity = sev;
  if (m_currSeverity > m_maxSeverity)
    m_maxSeverity = m_currSeverity;
  return *this;
}

ErrorStream &ErrorStream::operator <<(const ErrorLocation &loc) {
  m_location = loc;
  return *this;
}

ErrorStream &ErrorStream::operator << (ErrorStreamEnd obj) {
  output(m_msg.str());
  clear();
  return *this;
}

ErrorSeverity ErrorStream::reset() {
  ErrorSeverity old = m_maxSeverity;
  m_maxSeverity = sev_none;
  clear();
  return old;
}

void ErrorStream::clear() {
  m_currSeverity = sev_none;
  m_location = ErrorLocation();
  m_msg.str("");
  m_msg.clear();
}

void ErrorStream::output(const std::string &msg) {
  std::ostream &out = std::cerr;
  if (m_location.is_valid())
    out << to_string(m_location) << ": ";
  if (m_currSeverity != sev_none) {
    out << to_string(m_currSeverity) << ": ";
  }
  out << msg << std::endl;
}

std::string to_string(ErrorSeverity sev) {
  if (sev >= sev_none && sev <= sev_fatal) {
    static const char *sev_str[] = { "none", "message", "warning", "error", "fatal" };
    return sev_str[sev];
  }
  return "<unknown severity>";
}

std::string to_string(const ErrorLocation &loc) {
  std::string result = loc.filename_;
  if (loc.line_ > 0) {
    result += ":";
    result += std::to_string(loc.line_);
    if (loc.column_ > 0) {
      result += ":";
      result += std::to_string(loc.column_);
    }
  }
  return result;
}

} // namespace ACBase
