exml 0.7.2

Pure Rust XML library based on libxml2
Documentation
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
use std::{borrow::Cow, ptr::null_mut};

use crate::{
    error::{__xml_raise_error, XmlErrorDomain, XmlErrorLevel, XmlParserErrors},
    globals::{GenericError, StructuredError},
    libxml::relaxng::{
        FLAGS_IGNORABLE, FLAGS_NEGATIVE, FLAGS_NOERROR, XmlRelaxNGValidErr, XmlRelaxNGValidError,
    },
    tree::XmlGenericNodePtr,
};

const ERROR_IS_DUP: i32 = 1;

/// Computes a formatted error string for the given error code and args
///
/// Returns the error string, it must be deallocated by the caller
#[doc(alias = "xmlRelaxNGGetErrorString")]
fn xml_relaxng_get_error_string(
    err: XmlRelaxNGValidErr,
    arg1: Option<&str>,
    arg2: Option<&str>,
) -> Option<String> {
    let arg1 = arg1.unwrap_or("");
    let arg2 = arg2.unwrap_or("");

    match err {
        XmlRelaxNGValidErr::XmlRelaxngOk => None,
        XmlRelaxNGValidErr::XmlRelaxngErrMemory => Some("out of memory\n".to_string()),
        XmlRelaxNGValidErr::XmlRelaxngErrType => Some(format!("failed to validate type {arg1}\n")),
        XmlRelaxNGValidErr::XmlRelaxngErrTypeval => {
            Some(format!("Type {arg1} doesn't allow value '{arg2}'\n"))
        }
        XmlRelaxNGValidErr::XmlRelaxngErrDupid => Some(format!("ID {arg1} redefined\n",)),
        XmlRelaxNGValidErr::XmlRelaxngErrTypecmp => {
            Some(format!("failed to compare type {arg1}\n"))
        }
        XmlRelaxNGValidErr::XmlRelaxngErrNostate => Some("Internal error: no state\n".to_string()),
        XmlRelaxNGValidErr::XmlRelaxngErrNodefine => {
            Some("Internal error: no define\n".to_string())
        }
        XmlRelaxNGValidErr::XmlRelaxngErrInternal => Some(format!("Internal error: {arg1}\n")),
        XmlRelaxNGValidErr::XmlRelaxngErrListextra => Some(format!("Extra data in list: {arg1}\n")),
        XmlRelaxNGValidErr::XmlRelaxngErrInternodata => {
            Some("Internal: interleave block has no data\n".to_string())
        }
        XmlRelaxNGValidErr::XmlRelaxngErrInterseq => {
            Some("Invalid sequence in interleave\n".to_string())
        }
        XmlRelaxNGValidErr::XmlRelaxngErrInterextra => {
            Some(format!("Extra element {arg1} in interleave\n",))
        }
        XmlRelaxNGValidErr::XmlRelaxngErrElemname => {
            Some(format!("Expecting element {arg1}, got {arg2}\n"))
        }
        XmlRelaxNGValidErr::XmlRelaxngErrElemnons => {
            Some(format!("Expecting a namespace for element {arg1}\n"))
        }
        XmlRelaxNGValidErr::XmlRelaxngErrElemwrongns => Some(format!(
            "Element {arg1} has wrong namespace: expecting {arg2}\n"
        )),
        XmlRelaxNGValidErr::XmlRelaxngErrElemwrong => {
            Some(format!("Did not expect element {arg1} there\n"))
        }
        XmlRelaxNGValidErr::XmlRelaxngErrTextwrong => {
            Some(format!("Did not expect text in element {arg1} content\n"))
        }
        XmlRelaxNGValidErr::XmlRelaxngErrElemextrans => {
            Some(format!("Expecting no namespace for element {arg1}\n"))
        }
        XmlRelaxNGValidErr::XmlRelaxngErrElemnotempty => {
            Some(format!("Expecting element {arg1} to be empty\n"))
        }
        XmlRelaxNGValidErr::XmlRelaxngErrNoelem => {
            Some(format!("Expecting an element {arg1}, got nothing\n"))
        }
        XmlRelaxNGValidErr::XmlRelaxngErrNotelem => {
            Some("Expecting an element got text\n".to_string())
        }
        XmlRelaxNGValidErr::XmlRelaxngErrAttrvalid => {
            Some(format!("Element {arg1} failed to validate attributes\n"))
        }
        XmlRelaxNGValidErr::XmlRelaxngErrContentvalid => {
            Some(format!("Element {arg1} failed to validate content\n"))
        }
        XmlRelaxNGValidErr::XmlRelaxngErrExtracontent => {
            Some(format!("Element {arg1} has extra content: {arg2}\n"))
        }
        XmlRelaxNGValidErr::XmlRelaxngErrInvalidattr => {
            Some(format!("Invalid attribute {arg1} for element {arg2}\n"))
        }
        XmlRelaxNGValidErr::XmlRelaxngErrLackdata => {
            Some(format!("Datatype element {arg1} contains no data\n"))
        }
        XmlRelaxNGValidErr::XmlRelaxngErrDataelem => {
            Some(format!("Datatype element {arg1} has child elements\n"))
        }
        XmlRelaxNGValidErr::XmlRelaxngErrValelem => {
            Some(format!("Value element {arg1} has child elements\n"))
        }
        XmlRelaxNGValidErr::XmlRelaxngErrListelem => {
            Some(format!("List element {arg1} has child elements\n"))
        }
        XmlRelaxNGValidErr::XmlRelaxngErrDatatype => {
            Some(format!("Error validating datatype {arg1}\n"))
        }
        XmlRelaxNGValidErr::XmlRelaxngErrValue => Some(format!("Error validating value {arg1}\n")),
        XmlRelaxNGValidErr::XmlRelaxngErrList => Some("Error validating list\n".to_string()),
        XmlRelaxNGValidErr::XmlRelaxngErrNogrammar => Some("No top grammar defined\n".to_string()),
        XmlRelaxNGValidErr::XmlRelaxngErrExtradata => {
            Some("Extra data in the document\n".to_string())
        }
        _ => Some("Unknown error !\n".to_string()),
    }
}

/// Handle a Relax NG Validation error
///
/// # Note
/// This method does not format the string.  
#[doc(alias = "xmlRngVErr")]
unsafe fn xml_rng_verr(
    ctxt: XmlRelaxNGValidCtxtPtr,
    node: Option<XmlGenericNodePtr>,
    error: i32,
    msg: &str,
    str1: Option<&str>,
    str2: Option<&str>,
) {
    unsafe {
        let mut schannel: Option<StructuredError> = None;
        let mut channel: Option<GenericError> = None;
        let mut data = None;

        if !ctxt.is_null() {
            if (*ctxt).serror.is_some() {
                schannel = (*ctxt).serror;
            } else {
                channel = (*ctxt).error;
            }
            data = (*ctxt).user_data.clone();
            (*ctxt).nb_errors += 1;
        }
        let error = XmlParserErrors::try_from(error).unwrap();
        __xml_raise_error!(
            schannel,
            channel,
            data,
            null_mut(),
            node,
            XmlErrorDomain::XmlFromRelaxngv,
            error,
            XmlErrorLevel::XmlErrError,
            None,
            0,
            str1.map(|s| s.to_owned().into()),
            str2.map(|s| s.to_owned().into()),
            None,
            0,
            0,
            Some(msg),
        );
    }
}

/// Show a validation error.
#[doc(alias = "xmlRelaxNGShowValidError")]
unsafe fn xml_relaxng_show_valid_error(
    ctxt: XmlRelaxNGValidCtxtPtr,
    err: XmlRelaxNGValidErr,
    node: Option<XmlGenericNodePtr>,
    child: Option<XmlGenericNodePtr>,
    arg1: Option<&str>,
    arg2: Option<&str>,
) {
    unsafe {
        if (*ctxt).flags & FLAGS_NOERROR != 0 {
            return;
        }

        let Some(message) = xml_relaxng_get_error_string(err, arg1, arg2) else {
            return;
        };

        if (*ctxt).err_no == XmlRelaxNGValidErr::XmlRelaxngOk as i32 {
            (*ctxt).err_no = err as i32;
        }
        xml_rng_verr(ctxt, child.or(node), err as _, message.as_str(), arg1, arg2);
    }
}

const MAX_ERROR: usize = 5;

/// Show all validation error over a given index.
#[doc(alias = "xmlRelaxNGDumpValidError")]
pub(crate) unsafe fn xml_relaxng_dump_valid_error(ctxt: XmlRelaxNGValidCtxtPtr) {
    unsafe {
        let mut k = 0;
        for (i, err) in (*ctxt).err_tab.iter_mut().enumerate() {
            if k < MAX_ERROR {
                if (*ctxt).err_tab[..i].iter().any(|dup| {
                    err.err == dup.err
                        && err.node == dup.node
                        && err.arg1 == dup.arg1
                        && err.arg2 == dup.arg2
                }) {
                    if err.flags & ERROR_IS_DUP != 0 {
                        err.arg1 = None;
                        err.arg2 = None;
                        err.flags = 0;
                    }
                    continue;
                }
                xml_relaxng_show_valid_error(
                    ctxt,
                    err.err,
                    err.node,
                    err.seq,
                    err.arg1.as_deref(),
                    err.arg2.as_deref(),
                );
                k += 1;
            }
        }

        (*ctxt).err_tab.clear();
    }
}

/// Pushes a new error on top of the error stack
///
/// Returns 0 in case of error, the index in the stack otherwise
#[doc(alias = "xmlRelaxNGValidErrorPush")]
unsafe fn xml_relaxng_valid_error_push(
    ctxt: XmlRelaxNGValidCtxtPtr,
    err: XmlRelaxNGValidErr,
    arg1: Option<&str>,
    arg2: Option<&str>,
    _dup: i32,
) -> i32 {
    unsafe {
        if let Some(last_error) = (*ctxt).err_tab.last() {
            if !(*ctxt).state.is_null()
                && last_error.node == (*(*ctxt).state).node
                && last_error.err == err
            {
                return (*ctxt).err_tab.len() as i32 - 1;
            }
        }
        let mut cur = XmlRelaxNGValidError {
            err,
            ..Default::default()
        };
        cur.arg1 = arg1.map(|arg| arg.to_owned());
        cur.arg2 = arg2.map(|arg| arg.to_owned());
        cur.flags = 0;
        if !(*ctxt).state.is_null() {
            cur.node = (*(*ctxt).state).node;
            cur.seq = (*(*ctxt).state).seq;
        } else {
            cur.node = None;
            cur.seq = None;
        }
        (*ctxt).err_tab.push(cur);
        (*ctxt).err_tab.len() as i32 - 1
    }
}

/// Pops the top error from the error stack
#[doc(alias = "xmlRelaxNGValidErrorPop")]
pub(crate) unsafe fn xml_relaxng_valid_error_pop(ctxt: XmlRelaxNGValidCtxtPtr) {
    unsafe {
        (*ctxt).err_tab.pop();
    }
}

/// pop and discard all errors until the given level is reached
#[doc(alias = "xmlRelaxNGPopErrors")]
pub(crate) unsafe fn xml_relaxng_pop_errors(ctxt: XmlRelaxNGValidCtxtPtr, level: i32) {
    unsafe {
        for err in (*ctxt).err_tab[level as usize..].iter_mut() {
            if err.flags & ERROR_IS_DUP != 0 {
                err.arg1 = None;
                err.arg2 = None;
                err.flags = 0;
            }
        }
        (*ctxt).err_tab.truncate(level as usize);
    }
}

/// Register a validation error, either generating it if it's sure
/// or stacking it for later handling if unsure.
#[doc(alias = "xmlRelaxNGAddValidError")]
pub(crate) unsafe fn xml_relaxng_add_valid_error(
    ctxt: XmlRelaxNGValidCtxtPtr,
    err: XmlRelaxNGValidErr,
    arg1: Option<&str>,
    arg2: Option<&str>,
    dup: i32,
) {
    unsafe {
        if ctxt.is_null() {
            return;
        }
        if (*ctxt).flags & FLAGS_NOERROR != 0 {
            return;
        }

        // generate the error directly
        if (*ctxt).flags & FLAGS_IGNORABLE == 0 || (*ctxt).flags & FLAGS_NEGATIVE != 0 {
            // Flush first any stacked error which might be the
            // real cause of the problem.
            if !(*ctxt).err_tab.is_empty() {
                xml_relaxng_dump_valid_error(ctxt);
            }
            let (mut node, seq) = if !(*ctxt).state.is_null() {
                ((*(*ctxt).state).node, (*(*ctxt).state).seq)
            } else {
                (None, None)
            };
            if node.is_none() && seq.is_none() {
                node = (*ctxt).pnode.map(|node| node.into());
            }
            xml_relaxng_show_valid_error(ctxt, err, node, seq, arg1, arg2);
        } else {
            // Stack the error for later processing if needed
            xml_relaxng_valid_error_push(ctxt, err, arg1, arg2, dup);
        }
    }
}

/// Handle a redefinition of attribute error
#[doc(alias = "xmlRngVErrMemory")]
pub(crate) unsafe fn xml_rng_verr_memory(ctxt: XmlRelaxNGValidCtxtPtr, extra: &str) {
    unsafe {
        let mut schannel: Option<StructuredError> = None;
        let mut channel: Option<GenericError> = None;
        let mut data = None;

        if !ctxt.is_null() {
            if let Some(serror) = (*ctxt).serror {
                schannel = Some(serror);
            } else {
                channel = (*ctxt).error;
            }
            data = (*ctxt).user_data.clone();
            (*ctxt).nb_errors += 1;
        }
        __xml_raise_error!(
            schannel,
            channel,
            data,
            null_mut(),
            None,
            XmlErrorDomain::XmlFromRelaxngv,
            XmlParserErrors::XmlErrNoMemory,
            XmlErrorLevel::XmlErrFatal,
            None,
            0,
            Some(extra.to_owned().into()),
            None,
            None,
            0,
            0,
            "Memory allocation failed : {}\n",
            extra
        );
    }
}

/// Handle a redefinition of attribute error
#[doc(alias = "xmlRngPErrMemory")]
pub(crate) unsafe fn xml_rng_perr_memory(ctxt: XmlRelaxNGParserCtxtPtr, extra: Option<&str>) {
    unsafe {
        let mut schannel: Option<StructuredError> = None;
        let mut channel: Option<GenericError> = None;
        let mut data = None;

        if !ctxt.is_null() {
            if (*ctxt).serror.is_some() {
                schannel = (*ctxt).serror;
            } else {
                channel = (*ctxt).error;
            }
            data = (*ctxt).user_data.clone();
            (*ctxt).nb_errors += 1;
        }
        if let Some(extra) = extra {
            __xml_raise_error!(
                schannel,
                channel,
                data,
                null_mut(),
                None,
                XmlErrorDomain::XmlFromRelaxngp,
                XmlParserErrors::XmlErrNoMemory,
                XmlErrorLevel::XmlErrFatal,
                None,
                0,
                Some(extra.to_owned().into()),
                None,
                None,
                0,
                0,
                "Memory allocation failed : {}\n",
                extra
            );
        } else {
            __xml_raise_error!(
                schannel,
                channel,
                data,
                null_mut(),
                None,
                XmlErrorDomain::XmlFromRelaxngp,
                XmlParserErrors::XmlErrNoMemory,
                XmlErrorLevel::XmlErrFatal,
                None,
                0,
                None,
                None,
                None,
                0,
                0,
                "Memory allocation failed\n",
            );
        }
    }
}

pub(crate) unsafe fn xml_rng_err_internal(
    ctxt: *mut XmlRelaxNGParserCtxt,
    node: Option<XmlGenericNodePtr>,
    error: XmlParserErrors,
    msg: &str,
    str1: Option<Cow<'static, str>>,
    str2: Option<Cow<'static, str>>,
) {
    unsafe {
        let mut schannel: Option<StructuredError> = None;
        let mut channel: Option<GenericError> = None;
        let mut data = None;

        if !ctxt.is_null() {
            if (*ctxt).serror.is_some() {
                schannel = (*ctxt).serror;
            } else {
                channel = (*ctxt).error;
            }
            data = (*ctxt).user_data.clone();
            (*ctxt).nb_errors += 1;
        }
        __xml_raise_error!(
            schannel,
            channel,
            data,
            null_mut(),
            node,
            XmlErrorDomain::XmlFromRelaxngp,
            error,
            XmlErrorLevel::XmlErrError,
            None,
            0,
            str1,
            str2,
            None,
            0,
            0,
            Some(msg),
        );
    }
}

/// Handle a Relax NG Parsing error
#[doc(alias = "xmlRngPErr")]
macro_rules! xml_rng_perr {
    ($ctxt:expr, $node:expr, $error:expr, $msg:literal) => {
        xml_rng_perr!(@inner, $ctxt, $node, $error, $msg, None, None);
    };
    ($ctxt:expr, $node:expr, $error:expr, $msg:literal, $str1:expr) => {
        let msg = format!($msg, $str1);
        xml_rng_perr!(
            @inner,
            $ctxt,
            $node,
            $error,
            &msg,
            Some($str1.to_owned().into()),
            None
        );
    };
    ($ctxt:expr, $node:expr, $error:expr, $msg:literal, $str1:expr, $str2:expr) => {
        let msg = format!($msg, $str1, $str2);
        xml_rng_perr!(
            @inner,
            $ctxt,
            $node,
            $error,
            &msg,
            Some($str1.to_owned().into()),
            Some($str2.to_owned().into())
        );
    };
    (@inner, $ctxt:expr, $node:expr, $error:expr, $msg:expr, $str1:expr, $str2:expr) => {
        // If this function is expanded at here,  stack overflow occurs...
        $crate::relaxng::xml_rng_err_internal($ctxt as _, $node as _, $error, $msg, $str1, $str2);
    };
}
pub(crate) use xml_rng_perr;

macro_rules! VALID_ERR {
    ($ctxt:expr, $a:expr) => {
        $crate::relaxng::xml_relaxng_add_valid_error($ctxt, $a, None, None, 0);
    };
}
macro_rules! VALID_ERR2 {
    ($ctxt:expr, $a:expr, $b:expr) => {
        $crate::relaxng::xml_relaxng_add_valid_error($ctxt, $a, $b, None, 0);
    };
}
macro_rules! VALID_ERR3 {
    ($ctxt:expr, $a:expr, $b:expr, $c:expr) => {
        $crate::relaxng::xml_relaxng_add_valid_error($ctxt, $a, $b, $c, 0);
    };
}
macro_rules! VALID_ERR2P {
    ($ctxt:expr, $a:expr, $b:expr) => {
        $crate::relaxng::xml_relaxng_add_valid_error($ctxt, $a, $b, None, 1);
    };
}
macro_rules! VALID_ERR3P {
    ($ctxt:expr, $a:expr, $b:expr, $c:expr) => {
        $crate::relaxng::xml_relaxng_add_valid_error($ctxt, $a, $b, $c, 1);
    };
}
pub(crate) use VALID_ERR;
pub(crate) use VALID_ERR2;
pub(crate) use VALID_ERR2P;
pub(crate) use VALID_ERR3;
pub(crate) use VALID_ERR3P;

use super::{XmlRelaxNGParserCtxt, XmlRelaxNGParserCtxtPtr, XmlRelaxNGValidCtxtPtr};