Rename all source files from - to _ for consistency.
[alexxy/gromacs.git] / src / testutils / refdata_xml.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2015,2016,2017,2019, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35 /*! \internal \file
36  * \brief
37  * Implements reference data XML persistence.
38  *
39  * \author Teemu Murtola <teemu.murtola@gmail.com>
40  * \author Mark Abraham <mark.j.abraham@gmail.com>
41  * \ingroup module_testutils
42  */
43 #include "gmxpre.h"
44
45 #include "refdata_xml.h"
46
47 #include <tinyxml2.h>
48
49 #include "gromacs/utility/exceptions.h"
50
51 #include "testutils/refdata_impl.h"
52 #include "testutils/testexceptions.h"
53
54 namespace gmx
55 {
56 namespace test
57 {
58
59 namespace
60 {
61
62 //! XML version declaration used when writing the reference data.
63 const char *const c_VersionDeclarationString = "xml version=\"1.0\"";
64 //! XML stylesheet declaration used for writing the reference data.
65 const char *const c_StyleSheetDeclarationString = "xml-stylesheet type=\"text/xsl\" href=\"referencedata.xsl\"";
66 //! Name of the root element in reference data XML files.
67 const char *const c_RootNodeName = "ReferenceData";
68 //! Name of the XML attribute used to store identifying strings for reference data elements.
69 const char *const c_IdAttrName = "Name";
70
71 }       // namespace
72
73 /********************************************************************
74  * XML reading
75  */
76
77 namespace
78 {
79
80 //! Convenience typedef
81 typedef tinyxml2::XMLDocument *XMLDocumentPtr;
82 //! Convenience typedef
83 typedef tinyxml2::XMLNode *XMLNodePtr;
84 //! Convenience typedef
85 typedef tinyxml2::XMLElement *XMLElementPtr;
86 //! Convenience typedef
87 typedef tinyxml2::XMLText *XMLTextPtr;
88
89 //! \name Helper functions for XML reading
90 //! \{
91
92 void readEntry(XMLNodePtr node, ReferenceDataEntry *entry);
93
94 XMLNodePtr getCDataChildNode(XMLNodePtr node)
95 {
96     XMLNodePtr cdata = node->FirstChild();
97     while (cdata != nullptr &&
98            cdata->ToText() != nullptr &&
99            !cdata->ToText()->CData())
100     {
101         cdata = cdata->NextSibling();
102     }
103     return cdata;
104 }
105
106 bool hasCDataContent(XMLNodePtr node)
107 {
108     return getCDataChildNode(node) != nullptr;
109 }
110
111 //! Return a node convertible to text, either \c childNode or its first such sibling.
112 XMLNodePtr getNextTextChildNode(XMLNodePtr childNode)
113 {
114     // Note that when reading, we don't have to care if it is in a
115     // CDATA section, or not.
116     while (childNode != nullptr)
117     {
118         if (childNode->ToText() != nullptr)
119         {
120             break;
121         }
122         childNode = childNode->NextSibling();
123     }
124     return childNode;
125 }
126
127 //! Return the concatenation of all the text children of \c node, including multiple CDATA children.
128 std::string getValueFromLeafElement(XMLNodePtr node)
129 {
130     std::string value;
131
132     XMLNodePtr  childNode = getNextTextChildNode(node->FirstChild());
133     while (childNode != nullptr)
134     {
135         value += std::string(childNode->Value());
136
137         childNode = getNextTextChildNode(childNode->NextSibling());
138     }
139
140     if (hasCDataContent(node))
141     {
142         // Prepare to strip the convenience newline added in
143         // createElementContents, when writing CDATA content for
144         // StringBlock data.
145         if (value.empty() || value[0] != '\n')
146         {
147             GMX_THROW(TestException("Invalid string block in reference data"));
148         }
149         value.erase(0, 1);
150     }
151
152     return value;
153 }
154
155 //! Make a new entry from \c element.
156 ReferenceDataEntry::EntryPointer createEntry(XMLElementPtr element)
157 {
158     const char *id = element->Attribute(c_IdAttrName);
159     ReferenceDataEntry::EntryPointer entry(new ReferenceDataEntry(element->Value(), id));
160     return entry;
161 }
162
163 //! Read the child entries of \c parentElement and transfer the contents to \c entry
164 void readChildEntries(XMLNodePtr parentElement, ReferenceDataEntry *entry)
165 {
166     XMLElementPtr childElement = parentElement->FirstChildElement();
167     while (childElement != nullptr)
168     {
169         ReferenceDataEntry::EntryPointer child(createEntry(childElement));
170         readEntry(childElement, child.get());
171         entry->addChild(move(child));
172         childElement = childElement->NextSiblingElement();
173     }
174 }
175
176 //! Return whether \c node has child XML elements (rather than text content).
177 bool isCompoundElement(XMLNodePtr node)
178 {
179     return node->FirstChildElement() != nullptr;
180 }
181
182 //! Read \c element and transfer the contents to \c entry
183 void readEntry(XMLNodePtr element, ReferenceDataEntry *entry)
184 {
185     if (isCompoundElement(element))
186     {
187         readChildEntries(element, entry);
188     }
189     else if (hasCDataContent(element))
190     {
191         entry->setTextBlockValue(getValueFromLeafElement(element));
192     }
193     else
194     {
195         entry->setValue(getValueFromLeafElement(element));
196     }
197 }
198
199 //! \}
200
201 }       // namespace
202
203 //! \cond internal
204 ReferenceDataEntry::EntryPointer
205 readReferenceDataFile(const std::string &path)
206 {
207     tinyxml2::XMLDocument document;
208     document.LoadFile(path.c_str());
209     if (document.Error())
210     {
211         const char *errorStr1 = document.GetErrorStr1();
212         const char *errorStr2 = document.GetErrorStr2();
213         std::string errorString("Error was ");
214         if (errorStr1)
215         {
216             errorString += errorStr1;
217         }
218         if (errorStr2)
219         {
220             errorString += errorStr2;
221         }
222         if (!errorStr1 && !errorStr2)
223         {
224             errorString += "not specified.";
225         }
226         GMX_THROW(TestException("Reference data not parsed successfully: " + path + "\n." + errorString + "\n"));
227     }
228     XMLElementPtr rootNode = document.RootElement();
229     if (rootNode == nullptr)
230     {
231         GMX_THROW(TestException("Reference data is empty: " + path));
232     }
233     if (std::strcmp(rootNode->Value(), c_RootNodeName) != 0)
234     {
235         GMX_THROW(TestException("Invalid root node type in " + path));
236     }
237
238     ReferenceDataEntry::EntryPointer rootEntry(ReferenceDataEntry::createRoot());
239     readEntry(rootNode, rootEntry.get());
240     return rootEntry;
241 }
242 //! \endcond
243
244 /********************************************************************
245  * XML writing
246  */
247
248 namespace
249 {
250
251 //! \name Helper functions for XML writing
252 //! \{
253
254 void createElementAndContents(XMLElementPtr             parentElement,
255                               const ReferenceDataEntry &entry);
256
257 void setIdAttribute(XMLElementPtr element, const std::string &id)
258 {
259     if (!id.empty())
260     {
261         element->SetAttribute(c_IdAttrName, id.c_str()); // If this fails, it throws std::bad_alloc
262     }
263 }
264
265 XMLElementPtr createElement(XMLElementPtr parentElement, const ReferenceDataEntry &entry)
266 {
267     XMLElementPtr element = parentElement->GetDocument()->NewElement(entry.type().c_str());
268     parentElement->InsertEndChild(element);
269     setIdAttribute(element, entry.id()); // If this fails, it throws std::bad_alloc
270     return element;
271 }
272
273 void createChildElements(XMLElementPtr parentElement, const ReferenceDataEntry &entry)
274 {
275     const ReferenceDataEntry::ChildList &children(entry.children());
276     ReferenceDataEntry::ChildIterator    child;
277     for (child = children.begin(); child != children.end(); ++child)
278     {
279         createElementAndContents(parentElement, **child);
280     }
281 }
282
283 /*! \brief Handle \c input intended to be written as CDATA
284  *
285  * This method searches for any ']]>' sequences embedded in \c input,
286  * because this must always end a CDATA field. If any are found, it
287  * breaks the string so that instead multiple CDATA fields will be
288  * written with that token sequence split across the fields. Note that
289  * tinyxml2 does not handle such things itself.
290  *
291  * This is an edge case that is unimportant for GROMACS refdata, but
292  * it is preferable to know that the infrastructure won't break.
293  */
294 std::vector<std::string> breakUpAnyCdataEndTags(const std::string &input)
295 {
296     std::vector<std::string> strings;
297     std::size_t              startPos = 0;
298     std::size_t              endPos;
299
300     do
301     {
302         endPos = input.find("]]>", startPos);
303         if (endPos != std::string::npos)
304         {
305             // We found an embedded CDATA end tag, so arrange to split it into multiple CDATA blocks
306             endPos++;
307         }
308         strings.push_back(input.substr(startPos, endPos));
309         startPos = endPos;
310     }
311     while (endPos != std::string::npos);
312
313     return strings;
314 }
315
316 void createElementContents(XMLElementPtr element, const ReferenceDataEntry &entry)
317 {
318     // TODO: Figure out if \r and \r\n can be handled without them
319     // changing to \n in the roundtrip.
320     if (entry.isCompound())
321     {
322         createChildElements(element, entry);
323     }
324     else if (entry.isTextBlock())
325     {
326         // An extra newline is written in the beginning to make lines align
327         // in the output xml (otherwise, the first line would be off by the length
328         // of the starting CDATA tag).
329         const std::string        adjustedValue = "\n" + entry.value();
330         std::vector<std::string> cdataStrings  = breakUpAnyCdataEndTags(adjustedValue);
331         for (auto const &s : cdataStrings)
332         {
333             XMLTextPtr textNode = element->GetDocument()->NewText(s.c_str());
334             textNode->SetCData(true);
335             element->InsertEndChild(textNode);
336         }
337     }
338     else
339     {
340         XMLTextPtr textNode = element->GetDocument()->NewText(entry.value().c_str());
341         element->InsertEndChild(textNode);
342     }
343 }
344
345 void createElementAndContents(XMLElementPtr parentElement, const ReferenceDataEntry &entry)
346 {
347     XMLElementPtr element = createElement(parentElement, entry);
348     createElementContents(element, entry);
349 }
350
351 XMLElementPtr createRootElement(XMLDocumentPtr document)
352 {
353     XMLElementPtr rootElement = document->NewElement(c_RootNodeName);
354     document->InsertEndChild(rootElement);
355     return rootElement;
356 }
357
358 //! \}
359
360 }       // namespace
361
362 //! \cond internal
363 void writeReferenceDataFile(const std::string        &path,
364                             const ReferenceDataEntry &rootEntry)
365 {
366     // TODO: Error checking
367     tinyxml2::XMLDocument     document;
368
369     tinyxml2::XMLDeclaration *declaration = document.NewDeclaration(c_VersionDeclarationString);
370     document.InsertEndChild(declaration);
371
372     declaration = document.NewDeclaration(c_StyleSheetDeclarationString);
373     document.InsertEndChild(declaration);
374
375     XMLElementPtr rootElement = createRootElement(&document);
376     createChildElements(rootElement, rootEntry);
377
378     if (document.SaveFile(path.c_str()) != tinyxml2::XML_NO_ERROR)
379     {
380         GMX_THROW(TestException("Reference data saving failed in " + path));
381     }
382 }
383 //! \endcond
384
385 } // namespace test
386 } // namespace gmx