// $Id: xml.cpp,v 1.125 2018/01/03 21:33:06 mkkuhner Exp $

/*
Copyright 2002-2005 Mary K. Kuhner, Peter Beerli, and Joseph Felsenstein

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

*/

/* Authors: Peter Beerli, Mary Kuhner, Jon Yamato and Joseph Felsenstein */


#include <cassert>

#include "errhandling.h"
#include "front_end_warnings.h"
#include "stringx.h"
#include "tinyxml.h"
#include "xml.h"
#include "xml_strings.h"

using std::string;

//------------------------------------------------------------------------------------

XmlErrorSupport::XmlErrorSupport(string fileName)
    :
    m_fileName(fileName),
    m_errorMessage("")
{
}

XmlErrorSupport::~XmlErrorSupport()
{
}

string
XmlErrorSupport::GetFileName()
{
    return m_fileName;
}

void
XmlErrorSupport::ThrowDataError(const string& reason)
{
    m_errorMessage.append(xmlstr::XML_ERR_DATA_ERR_0 + reason);
    incorrect_data e(m_errorMessage);
    throw e;
}

void
XmlErrorSupport::ThrowDataError(const string& reason, long lineno)
{
    m_errorMessage.append( xmlstr::XML_ERR_DATA_ERR_0
                           + xmlstr::XML_ERR_DATA_ERR_1
                           + m_fileName
                           + xmlstr::XML_ERR_DATA_ERR_2
                           + ToString(lineno)
                           + xmlstr::XML_ERR_DATA_ERR_3
                           + reason);
    incorrect_data e(m_errorMessage);
    throw e;
}

void
XmlErrorSupport::ThrowFileError(const string& reason)
{
    m_errorMessage.append(xmlstr::XML_ERR_FILE_ERR + reason);
    file_error e(m_errorMessage);
    throw e;
}

void
XmlErrorSupport::ThrowXMLError(const string& reason)
{
    m_errorMessage.append(xmlstr::XML_ERR_0 + reason);
    incorrect_xml e(m_errorMessage);
    throw e;
}

void
XmlErrorSupport::ThrowXMLError(const string& reason, long lineno)
{
    m_errorMessage.append(xmlstr::XML_ERR_0
                          + xmlstr::XML_ERR_1
                          + m_fileName
                          + xmlstr::XML_ERR_2
                          + ToString(lineno)
                          + xmlstr::XML_ERR_3
                          + reason);
    incorrect_xml e(m_errorMessage);
    throw e;
}

void
XmlErrorSupport::ThrowInternalXMLError(const string& reason)
{
    m_errorMessage.append(xmlstr::XML_ERR_INTERNAL + reason);
    incorrect_xml e(m_errorMessage);
    throw e;
}

//------------------------------------------------------------------------------------

XmlParser::XmlParser(ParseTreeSchema & schema, FrontEndWarnings & warnings)
    :
    XmlErrorSupport(defaults::datafilename),
    m_schema(schema),
    m_frontEndWarnings(warnings)
{
}

XmlParser::~XmlParser()
{
}

void
XmlParser::ParseFileData(string fileName)
{
    m_fileName = fileName;
    m_document.LoadFile(GetFileName());
    if(m_document.Error())
    {
        throw tixml_error(m_document.ErrorDesc());  // EWFIX -- row ??
    }
    else
        // XML parser is happy, but now we need to make
        // sure that we've got data
    {
        TiXmlElement * root = GetRootElement();
        if(root == NULL)
        {
            string msg = GetFileName() + ":"
                + xmlstr::XML_ERR_NO_XML_DATA;
            throw tixml_error(msg);
        }
    }

    checkSchema();
}

TiXmlElement *
XmlParser::GetRootElement()
{
    return m_document.RootElement();
}

void
XmlParser::checkSchema()
{
    TiXmlElement * rootElement = GetRootElement();
    TiXmlNode * extraNode = rootElement->NextSibling();
    while(extraNode != NULL)
    {
        if(extraNode->Type() != TiXmlNode::TINYXML_COMMENT)
        {
            ThrowXMLError( xmlstr::XML_ERR_EXTRA_TAG_TOP_0
                           + extraNode->Value()
                           + xmlstr::XML_ERR_EXTRA_TAG_TOP_1,
                           extraNode->Row());
        }
        extraNode = extraNode->NextSibling();
    }
    checkSchema(rootElement);
}

void
XmlParser::checkAttrPresent(TiXmlElement * elem, string attrName)
{
    const string * attrValue = elem->Attribute(attrName);
    if(!attrValue)
    {
        ThrowXMLError( xmlstr::XML_ERR_ATTR_MISSING_0
                       +attrName
                       +xmlstr::XML_ERR_ATTR_MISSING_1
                       +elem->Value()
                       +xmlstr::XML_ERR_ATTR_MISSING_2,
                       elem->Row());

    }
}

void
XmlParser::checkElemPresent(TiXmlElement * elem, string elemName)
{
    TiXmlNode * firstChild = elem->IterateChildren(elemName,NULL);
    if(firstChild == NULL)
    {
        ThrowXMLError( xmlstr::XML_ERR_ELEM_MISSING_0
                       +elemName
                       +xmlstr::XML_ERR_ELEM_MISSING_1
                       +elem->Value()
                       +xmlstr::XML_ERR_ELEM_MISSING_2,
                       elem->Row());
    }
}

void
XmlParser::checkAttrAllowed(TiXmlElement * parent, string attrName)
{
    if(!m_schema.AllowsAttribute(string(parent->Value()),attrName,parent->Row()))
    {
        ThrowXMLError(xmlstr::XML_ERR_UNEXPECTED_ATTR_0
                      + attrName
                      + xmlstr::XML_ERR_UNEXPECTED_ATTR_1
                      + parent->Value()
                      + xmlstr::XML_ERR_UNEXPECTED_ATTR_2,
                      parent->Row());
    }
}

void
XmlParser::checkElemCount(TiXmlElement * parent, string childName)
{
    TiXmlNode * child = parent->IterateChildren(childName,NULL);
    assert(child != NULL);  // because we found it as child of parent

    if(!m_schema.AllowsElement(string(parent->Value()),childName,child->Row()))
    {
        ThrowXMLError(xmlstr::XML_ERR_UNEXPECTED_TAG_0
                      + childName
                      + xmlstr::XML_ERR_UNEXPECTED_TAG_1
                      + parent->Value()
                      + xmlstr::XML_ERR_UNEXPECTED_TAG_2,
                      child->Row());
    }

    // now check if there is more than one
    child = parent->IterateChildren(childName,child);
    if(child != NULL)
    {
        if(!m_schema.AllowsAdditionalElements(string(parent->Value()),childName,child->Row()))
        {
            ThrowXMLError(xmlstr::XML_ERR_EXTRA_TAG_0
                          + childName
                          + xmlstr::XML_ERR_EXTRA_TAG_1
                          + parent->Value()
                          + xmlstr::XML_ERR_EXTRA_TAG_2,
                          child->Row());
        }
    }
}

void
XmlParser::checkSchema(TiXmlElement * parentElem)
{

    string parentString(parentElem->Value());

    // check all required attributes are present
    std::set<string> attrs = m_schema.RequiredAttributes(parentString,parentElem->Row());
    for(std::set<string>::const_iterator i= attrs.begin(); i != attrs.end(); i++)
    {
        checkAttrPresent(parentElem,*i);
    }

    // check all required elements are present
    std::set<string> elems = m_schema.RequiredElements(parentString,parentElem->Row());
    for(std::set<string>::const_iterator i= elems.begin(); i != elems.end(); i++)
    {
        checkElemPresent(parentElem,*i);
    }

    // check all attributes present are allowed
    for(TiXmlAttribute * attr = parentElem->FirstAttribute(); attr != NULL; attr = attr->Next())
    {
        string attrName(attr->Name());
        checkAttrAllowed(parentElem,attrName);
    }

    // check all elements present are allowed and in right number
    TiXmlNode * child = NULL;
    while ((child = parentElem->IterateChildren(child)))
    {
        if(child->Type() == TiXmlNode::TINYXML_ELEMENT)
        {
            TiXmlElement * newElem = child->ToElement();
            string childString(newElem->Value());
            if(m_schema.DeprecatedElement(parentString,childString,newElem->Row()))
            {
                m_frontEndWarnings.AddWarning(xmlstr::XML_WARN_DEPRECATED_TAG_0
                                              + childString
                                              + xmlstr::XML_WARN_DEPRECATED_TAG_1
                                              + parentString
                                              + xmlstr::XML_WARN_DEPRECATED_TAG_2
                                              + ToString(newElem->Row()));
            }
            else
            {
                checkElemCount(parentElem,string(childString));
                checkSchema(newElem); // recursive check
            }
        }
    }
}

//____________________________________________________________________________________
