aboutsummaryrefslogtreecommitdiffstats
path: root/sources/shiboken6/ApiExtractor/xmlutils_libxslt.cpp
blob: 5a9a26913fd7f445c6976da02d37cadca9e0c631 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
// Copyright (C) 2019 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "xmlutils_libxslt.h"
#include "xmlutils.h"

#include "qtcompat.h"

#include <QtCore/QByteArray>
#include <QtCore/QCoreApplication>
#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QString>

#include <libxslt/xsltutils.h>
#include <libxslt/transform.h>

#include <libxml/xmlsave.h>
#include <libxml/xpath.h>

#include <cstdlib>
#include <memory>

using namespace Qt::StringLiterals;

static void cleanup()
{
    xsltCleanupGlobals();
    xmlCleanupParser();
}

static void ensureInitialized()
{
    static bool initialized = false;
    if (!initialized) {
        initialized = true;
        xmlInitParser();
        xsltInit();
        qAddPostRoutine(cleanup);
    }
}

// RAI Helpers for cleaning up libxml2/libxslt data

struct XmlDocDeleter // for std::unique_ptr<xmlDoc>
{
    void operator()(xmlDocPtr xmlDoc) { xmlFreeDoc(xmlDoc); }
};

struct XmlXPathObjectDeleter
{
    void operator()(xmlXPathObjectPtr xPathObject) { xmlXPathFreeObject(xPathObject); }
};

struct XmlStyleSheetDeleter // for std::unique_ptr<xsltStylesheet>
{
    void operator()(xsltStylesheetPtr xslt) { xsltFreeStylesheet(xslt); }
};

struct XmlXPathContextDeleter
{
    void operator()(xmlXPathContextPtr xPathContext) { xmlXPathFreeContext(xPathContext); }
};

using XmlDocUniquePtr = std::unique_ptr<xmlDoc, XmlDocDeleter>;
using XmlPathObjectUniquePtr = std::unique_ptr<xmlXPathObject, XmlXPathObjectDeleter>;
using XmlStyleSheetUniquePtr = std::unique_ptr<xsltStylesheet, XmlStyleSheetDeleter>;
using XmlXPathContextUniquePtr = std::unique_ptr<xmlXPathContext, XmlXPathContextDeleter>;

// Helpers for formatting nodes obtained from XPATH queries

static int qbXmlOutputWriteCallback(void *context, const char *buffer, int len)
{
    static_cast<QByteArray *>(context)->append(buffer, len);
    return len;
}

static int qbXmlOutputCloseCallback(void * /* context */) { return 0; }

static QByteArray formatNode(xmlNodePtr node, QString *errorMessage)
{
    QByteArray result;
    xmlSaveCtxtPtr saveContext =
        xmlSaveToIO(qbXmlOutputWriteCallback, qbXmlOutputCloseCallback,
                    &result, "UTF-8", 0);
    if (!saveContext) {
        *errorMessage = u"xmlSaveToIO() failed."_s;
        return result;
    }
    const long saveResult = xmlSaveTree(saveContext, node);
    xmlSaveClose(saveContext);
    if (saveResult < 0)
        *errorMessage = u"xmlSaveTree() failed."_s;
    return result;
}

// XPath expressions
class LibXmlXQuery : public XQuery
{
public:
    explicit LibXmlXQuery(XmlDocUniquePtr &doc, XmlXPathContextUniquePtr &xpathContext) :
       m_doc(std::move(doc)), m_xpathContext(std::move(xpathContext))
    {
        ensureInitialized();
    }

protected:
    QString doEvaluate(const QString &xPathExpression, QString *errorMessage) override;

private:
    XmlDocUniquePtr m_doc;
    XmlXPathContextUniquePtr m_xpathContext;
};

QString LibXmlXQuery::doEvaluate(const QString &xPathExpression, QString *errorMessage)
{
    const QByteArray xPathExpressionB = xPathExpression.toUtf8();
    auto xPathExpressionX = reinterpret_cast<const xmlChar *>(xPathExpressionB.constData());

    XmlPathObjectUniquePtr xPathObject(xmlXPathEvalExpression(xPathExpressionX, m_xpathContext.get()));
    if (!xPathObject) {
         *errorMessage = u"xmlXPathEvalExpression() failed for \""_s + xPathExpression
                         + u'"';
        return QString();
    }
    QString result;
    if (xmlNodeSetPtr nodeSet = xPathObject->nodesetval) {
        for (int n = 0, count = nodeSet->nodeNr; n < count; ++n) {
            auto node = nodeSet->nodeTab[n];
            if (node->type == XML_ELEMENT_NODE) {
                result += QString::fromLocal8Bit(formatNode(node, errorMessage));
                if (!errorMessage->isEmpty())
                    return QString();
            }
        }
    }
    return result;
}

std::shared_ptr<XQuery> libXml_createXQuery(const QString &focus, QString *errorMessage)
{
    XmlDocUniquePtr doc(xmlReadFile(QFile::encodeName(focus).constData(),
                        "utf-8", XML_PARSE_NOENT));
    if (!doc) {
        *errorMessage = u"libxml2: Cannot set focus to "_s + QDir::toNativeSeparators(focus);
        return {};
    }
    XmlXPathContextUniquePtr xpathContext(xmlXPathNewContext(doc.get()));
    if (!xpathContext) {
        *errorMessage = u"libxml2: xmlXPathNewContext() failed"_s;
        return {};
    }
    return std::shared_ptr<XQuery>(new LibXmlXQuery(doc, xpathContext));
}

// XSLT transformation

static constexpr auto xsltPrefix = R"(<?xml version="1.0" encoding="UTF-8" ?>
    <xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
)"_L1;

QString libXslt_transform(const QString &xml, QString xsl, QString *errorMessage)
{
    ensureInitialized();
    // Read XML data
    if (!xsl.startsWith(u"<?xml")) {
        xsl.prepend(xsltPrefix);
        xsl.append(u"</xsl:transform>"_s);
    }
    const QByteArray xmlData = xml.toUtf8();

    XmlDocUniquePtr xmlDoc(xmlReadMemory(xmlData.constData(), int(xmlData.size()),
                                         "", "utf-8", XML_PARSE_NOENT));
    if (!xmlDoc) {
        *errorMessage = u"xmlParseMemory() failed for XML."_s;
        return xml;
    }

    // Read XSL data as a XML file
    const QByteArray xslData = xsl.toUtf8();
    // xsltFreeStylesheet will delete this pointer
    xmlDocPtr xslDoc = xmlParseMemory(xslData.constData(), xslData.size());
    if (!xslDoc) {
        *errorMessage = u"xmlParseMemory() failed for XSL \""_s + xsl + u"\"."_s;
        return xml;
    };

    // Parse XSL data
    XmlStyleSheetUniquePtr xslt(xsltParseStylesheetDoc(xslDoc));
    if (!xslt) {
        *errorMessage = u"xsltParseStylesheetDoc() failed."_s;
        return xml;
    }

    // Apply XSL
    XmlDocUniquePtr xslResult(xsltApplyStylesheet(xslt.get(), xmlDoc.get(), nullptr));
    xmlChar *buffer = nullptr;
    int bufferSize;
    QString result;
    if (xsltSaveResultToString(&buffer, &bufferSize, xslResult.get(), xslt.get()) == 0) {
        result = QString::fromUtf8(reinterpret_cast<char*>(buffer), bufferSize);
        std::free(buffer);
    } else {
        *errorMessage = u"xsltSaveResultToString() failed."_s;
        result = xml;
    }
    return result.trimmed();
}