summaryrefslogtreecommitdiffstats
path: root/src/parser/xml_writer.cpp
blob: a2f6c2ff2c5cb160491bc3db7236355f221b4ece (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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <orcus/xml_writer.hpp>
#include <orcus/xml_namespace.hpp>
#include <orcus/string_pool.hpp>

#include <vector>

/** To markup code that coverity warns might throw exceptions
    which won't throw in practice, or where std::terminate is
    an acceptable response if they do
*/
#if defined(__COVERITY__)
#define suppress_fun_call_w_exception(expr)                            \
    do                                                                 \
    {                                                                  \
        try                                                            \
        {                                                              \
            expr;                                                      \
        }                                                              \
        catch (const std::exception& e)                                \
        {                                                              \
            std::cerr << "Fatal exception: " << e.what() << std::endl; \
            std::terminate();                                          \
        }                                                              \
    } while (false)
#else
#define suppress_fun_call_w_exception(expr)                            \
    do                                                                 \
    {                                                                  \
        expr;                                                          \
    } while (false)
#endif

namespace orcus {

namespace {

struct _elem
{
    xml_name_t name;
    std::vector<std::string_view> ns_aliases;
    bool open;

    _elem(const xml_name_t& _name) : name(_name), open(true) {}
};

struct _attr
{
    xml_name_t name;
    std::string_view value;

    _attr(const xml_name_t& _name, std::string_view _value) :
        name(_name),
        value(_value)
    {}
};

void write_content_encoded(std::string_view content, std::ostream& os)
{
    auto _flush = [&os](const char*& p0, const char* p)
    {
        size_t n = std::distance(p0, p);
        os.write(p0, n);
        p0 = nullptr;
    };

    constexpr std::string_view cv_lt = "&lt;";
    constexpr std::string_view cv_gt = "&gt;";
    constexpr std::string_view cv_amp = "&amp;";
    constexpr std::string_view cv_apos = "&apos;";
    constexpr std::string_view cv_quot = "&quot;";

    const char* p = content.data();
    const char* p_end = p + content.size();
    const char* p0 = nullptr;

    for (; p != p_end; ++p)
    {
        if (!p0)
            p0 = p;

        switch (*p)
        {
            case '<':
                _flush(p0, p);
                os.write(cv_lt.data(), cv_lt.size());
                break;
            case '>':
                _flush(p0, p);
                os.write(cv_gt.data(), cv_gt.size());
                break;
            case '&':
                _flush(p0, p);
                os.write(cv_amp.data(), cv_amp.size());
                break;
            case '\'':
                _flush(p0, p);
                os.write(cv_apos.data(), cv_apos.size());
                break;
            case '"':
                _flush(p0, p);
                os.write(cv_quot.data(), cv_quot.size());
                break;
        }
    }

    if (p0)
        _flush(p0, p);
}

} // anonymous namespace

struct xml_writer::scope::impl
{
    xml_writer* parent;
    xml_name_t elem;

    impl() : parent(nullptr) {}

    impl(xml_writer* _parent, const xml_name_t& _elem) :
        parent(_parent),
        elem(_elem)
    {
        parent->push_element(elem);
    }

    ~impl()
    {
        suppress_fun_call_w_exception(parent->pop_element());
    }
};

xml_writer::scope::scope(xml_writer* parent, const xml_name_t& elem) :
    mp_impl(std::make_unique<impl>(parent, elem))
{
}

xml_writer::scope::scope(scope&& other) :
    mp_impl(std::move(other.mp_impl))
{
    // NB: we shouldn't have to create an impl instance for the other object
    // since everything happens in the impl, and the envelop class doesn't
    // access the impl internals.
}

xml_writer::scope::~scope() {}

xml_writer::scope& xml_writer::scope::operator= (scope&& other)
{
    scope tmp(std::move(other));
    mp_impl.swap(tmp.mp_impl);
    return *this;
}

struct xml_writer::impl
{
    xmlns_repository& ns_repo;
    std::ostream& os;
    std::vector<_elem> elem_stack;
    std::vector<std::string_view> ns_decls;
    std::vector<_attr> attrs;

    string_pool str_pool;
    xmlns_repository repo;
    xmlns_context cxt;

    impl(xmlns_repository& _ns_repo, std::ostream& _os) :
        ns_repo(_ns_repo),
        os(_os),
        cxt(ns_repo.create_context())
    {}

    void print(const xml_name_t& name)
    {
        std::string_view alias = cxt.get_alias(name.ns);
        if (!alias.empty())
            os << alias << ':';
        os << name.name;
    }

    xml_name_t intern(const xml_name_t& name)
    {
        xml_name_t interned = name;
        interned.name = str_pool.intern(interned.name).first;
        return interned;
    }

    std::string_view intern(std::string_view value)
    {
        return str_pool.intern(value).first;
    }
};

xml_writer::xml_writer(xmlns_repository& ns_repo, std::ostream& os) :
    mp_impl(std::make_unique<impl>(ns_repo, os))
{
    os << "<?xml version=\"1.0\"?>";
}

xml_writer::xml_writer(xml_writer&& other) :
    mp_impl(std::move(other.mp_impl))
{
    other.mp_impl = std::make_unique<impl>(mp_impl->ns_repo, mp_impl->os);
}

xml_writer& xml_writer::operator= (xml_writer&& other)
{
    xml_writer tmp(std::move(other));
    mp_impl.swap(tmp.mp_impl);
    return *this;
}

void xml_writer::pop_elements()
{
    // Pop all the elements currently on the stack.
    while (!mp_impl->elem_stack.empty())
        pop_element();
}

xml_writer::~xml_writer()
{
    suppress_fun_call_w_exception(pop_elements());
}

void xml_writer::close_current_element()
{
    if (!mp_impl->elem_stack.empty() && mp_impl->elem_stack.back().open)
    {
        mp_impl->os << '>';
        mp_impl->elem_stack.back().open = false;
    }
}

xml_writer::scope xml_writer::push_element_scope(const xml_name_t& name)
{
    return scope(this, name);
}

void xml_writer::push_element(const xml_name_t& _name)
{
    close_current_element();

    auto& os = mp_impl->os;
    xml_name_t name = mp_impl->intern(_name);

    os << '<';
    mp_impl->print(name);

    for (std::string_view alias : mp_impl->ns_decls)
    {
        os << " xmlns";
        if (!alias.empty())
            os << ':' << alias;
        os << "=\"";
        xmlns_id_t ns = mp_impl->cxt.get(alias);
        os << ns << '"';
    }

    for (const _attr& attr : mp_impl->attrs)
    {
        os << ' ';
        mp_impl->print(attr.name);
        os << "=\"";
        os << attr.value << '"';
    }

    mp_impl->attrs.clear();
    mp_impl->ns_decls.clear();

    mp_impl->elem_stack.emplace_back(name);
}

xmlns_id_t xml_writer::add_namespace(std::string_view alias, std::string_view value)
{
    std::string_view alias_safe = mp_impl->intern(alias);
    xmlns_id_t ns = mp_impl->cxt.push(alias_safe, mp_impl->intern(value));
    mp_impl->ns_decls.push_back(alias_safe);
    return ns;
}

void xml_writer::add_attribute(const xml_name_t& name, std::string_view value)
{
    mp_impl->attrs.emplace_back(mp_impl->intern(name), mp_impl->intern(value));
}

void xml_writer::add_content(std::string_view content)
{
    close_current_element();
    write_content_encoded(content, mp_impl->os);
}

xml_name_t xml_writer::pop_element()
{
    auto& os = mp_impl->os;

    const _elem& elem = mp_impl->elem_stack.back();
    auto name = elem.name;

    if (elem.open)
    {
        // self-closing element.
        os << "/>";
    }
    else
    {
        os << "</";
        mp_impl->print(name);
        os << '>';
    }

    for (std::string_view alias : mp_impl->elem_stack.back().ns_aliases)
        mp_impl->cxt.pop(alias);

    mp_impl->elem_stack.pop_back();
    return name;
}

} // namespace orcus

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */