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
/* 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 https://mozilla.org/MPL/2.0/. */

//! Functions for validating and extracting qualified XML names.

use html5ever::{namespace_url, ns, LocalName, Namespace, Prefix};

use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
use crate::dom::bindings::str::DOMString;

/// Validate a qualified name. See <https://dom.spec.whatwg.org/#validate> for details.
pub fn validate_qualified_name(qualified_name: &str) -> ErrorResult {
    // Step 2.
    match xml_name_type(qualified_name) {
        XMLName::Invalid => Err(Error::InvalidCharacter),
        XMLName::Name => Err(Error::InvalidCharacter), // see whatwg/dom#671
        XMLName::QName => Ok(()),
    }
}

/// Validate a namespace and qualified name and extract their parts.
/// See <https://dom.spec.whatwg.org/#validate-and-extract> for details.
pub fn validate_and_extract(
    namespace: Option<DOMString>,
    qualified_name: &str,
) -> Fallible<(Namespace, Option<Prefix>, LocalName)> {
    // Step 1.
    let namespace = namespace_from_domstring(namespace);

    // Step 2.
    validate_qualified_name(qualified_name)?;

    let colon = ':';

    // Step 5.
    let mut parts = qualified_name.splitn(2, colon);

    let (maybe_prefix, local_name) = {
        let maybe_prefix = parts.next();
        let maybe_local_name = parts.next();

        debug_assert!(parts.next().is_none());

        if let Some(local_name) = maybe_local_name {
            debug_assert!(!maybe_prefix.unwrap().is_empty());

            (maybe_prefix, local_name)
        } else {
            (None, maybe_prefix.unwrap())
        }
    };

    debug_assert!(!local_name.contains(colon));

    match (namespace, maybe_prefix) {
        (ns!(), Some(_)) => {
            // Step 6.
            Err(Error::Namespace)
        },
        (ref ns, Some("xml")) if ns != &ns!(xml) => {
            // Step 7.
            Err(Error::Namespace)
        },
        (ref ns, p) if ns != &ns!(xmlns) && (qualified_name == "xmlns" || p == Some("xmlns")) => {
            // Step 8.
            Err(Error::Namespace)
        },
        (ns!(xmlns), p) if qualified_name != "xmlns" && p != Some("xmlns") => {
            // Step 9.
            Err(Error::Namespace)
        },
        (ns, p) => {
            // Step 10.
            Ok((ns, p.map(Prefix::from), LocalName::from(local_name)))
        },
    }
}

/// Results of `xml_name_type`.
#[derive(PartialEq)]
#[allow(missing_docs)]
pub enum XMLName {
    QName,
    Name,
    Invalid,
}

/// Check if an element name is valid. See <http://www.w3.org/TR/xml/#NT-Name>
/// for details.
pub fn xml_name_type(name: &str) -> XMLName {
    fn is_valid_start(c: char) -> bool {
        matches!(c, ':' |
            'A'..='Z' |
            '_' |
            'a'..='z' |
            '\u{C0}'..='\u{D6}' |
            '\u{D8}'..='\u{F6}' |
            '\u{F8}'..='\u{2FF}' |
            '\u{370}'..='\u{37D}' |
            '\u{37F}'..='\u{1FFF}' |
            '\u{200C}'..='\u{200D}' |
            '\u{2070}'..='\u{218F}' |
            '\u{2C00}'..='\u{2FEF}' |
            '\u{3001}'..='\u{D7FF}' |
            '\u{F900}'..='\u{FDCF}' |
            '\u{FDF0}'..='\u{FFFD}' |
            '\u{10000}'..='\u{EFFFF}')
    }

    fn is_valid_continuation(c: char) -> bool {
        is_valid_start(c) ||
            matches!(c,
                '-' |
                '.' |
                '0'..='9' |
                '\u{B7}' |
                '\u{300}'..='\u{36F}' |
                '\u{203F}'..='\u{2040}')
    }

    let mut iter = name.chars();
    let mut non_qname_colons = false;
    let mut seen_colon = false;
    let mut last = match iter.next() {
        None => return XMLName::Invalid,
        Some(c) => {
            if !is_valid_start(c) {
                return XMLName::Invalid;
            }
            if c == ':' {
                non_qname_colons = true;
            }
            c
        },
    };

    for c in iter {
        if !is_valid_continuation(c) {
            return XMLName::Invalid;
        }
        if c == ':' {
            if seen_colon {
                non_qname_colons = true;
            } else {
                seen_colon = true;
            }
        }
        last = c
    }

    if last == ':' {
        non_qname_colons = true
    }

    if non_qname_colons {
        XMLName::Name
    } else {
        XMLName::QName
    }
}

/// Convert a possibly-null URL to a namespace.
///
/// If the URL is None, returns the empty namespace.
pub fn namespace_from_domstring(url: Option<DOMString>) -> Namespace {
    match url {
        None => ns!(),
        Some(s) => Namespace::from(s),
    }
}