Skip to main content

atmos/os_lib/web_apis/builtins/
dom_ns.rs

1// 名前空間つきの要素(`createElementNS`・`namespaceURI`・`prefix`・`localName`・`tagName`)と名前の検査
2// (2026-11-19、DOM Standard §4.5「validate and extract」。WPT `dom/nodes/Document-createElementNS.html` など)。
3//
4// 要素の名前空間は `DomNode::attrs` の内部属性(`_` 始まり。属性の一覧・直列化には出ない)に持つ:
5//   `_ns`     名前空間 URI(空文字列=名前空間なし)。無ければ HTML 名前空間(従来どおり)。
6//   `_qname`  作ったときの修飾名そのまま(大文字小文字を保つ)。無ければ `tag`。
7//   `_prefix` 接頭辞。
8// `tag` は従来どおり小文字の局所名(CSS・レイアウトが見る)。
9use super::*;
10
11pub(crate) const HTML_NS: &str = "http://www.w3.org/1999/xhtml";
12pub(crate) const SVG_NS: &str = "http://www.w3.org/2000/svg";
13pub(crate) const MATHML_NS: &str = "http://www.w3.org/1998/Math/MathML";
14pub(crate) const XML_NS: &str = "http://www.w3.org/XML/1998/namespace";
15pub(crate) const XMLNS_NS: &str = "http://www.w3.org/2000/xmlns/";
16
17/// 名前(`Name`)として使える文字列か。DOM Standard §4.5 `createElement` / XML Name
18/// 規則(先頭が ASCII 英字なら 2 文字目以降は NUL・ASCII 空白・`/`・`>` 以外。
19/// 先頭が `:`・`_`・非 ASCII なら 2 文字目以降は ASCII 英数字・`-`・`.`・`:`・`_`・非 ASCII)。
20pub(crate) fn is_valid_xml_name(s: &str) -> bool {
21    let mut it = s.chars();
22    let Some(first) = it.next() else { return false };
23    if first.is_ascii_alphabetic() {
24        it.all(|c| !matches!(c, '\0' | '\t' | '\n' | '\x0c' | '\r' | ' ' | '/' | '>'))
25    } else if first == ':' || first == '_' || (first as u32) >= 0x80 {
26        it.all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '.' | ':' | '_') || (c as u32) >= 0x80)
27    } else {
28        false
29    }
30}
31
32/// 名前の検査(`InvalidCharacterError`)。
33pub(crate) fn check_name(it: &Interp, s: &str) -> Result<(), Value> {
34    if is_valid_xml_name(s) {
35        Ok(())
36    } else {
37        Err(it.dom_exception("InvalidCharacterError", "The string contains invalid characters."))
38    }
39}
40
41/// DOM Standard §4.5 validate and extract。`(名前空間, 接頭辞, 局所名)`。
42pub(crate) fn validate_and_extract(
43    it: &Interp,
44    namespace: Option<&str>,
45    qname: &str,
46) -> Result<(Option<String>, Option<String>, String), Value> {
47    let ns = namespace.filter(|s| !s.is_empty());
48    let (prefix, local) = match qname.split_once(':') {
49        Some((p, l)) => {
50            if p.is_empty()
51                || p.chars()
52                    .any(|c| matches!(c, ' ' | '\t' | '\n' | '\x0c' | '\r' | '/' | '>' | '\0'))
53                || !is_valid_xml_name(l)
54            {
55                return Err(it.dom_exception(
56                    "InvalidCharacterError",
57                    "The qualified name is not a valid QName.",
58                ));
59            }
60            (Some(p), l)
61        }
62        None => {
63            check_name(it, qname)?;
64            (None, qname)
65        }
66    };
67    let ns_err = |m: &str| Err(it.dom_exception("NamespaceError", m));
68    if prefix.is_some() && ns.is_none() {
69        return ns_err("A prefix requires a namespace.");
70    }
71    if prefix == Some("xml") && ns != Some(XML_NS) {
72        return ns_err("The 'xml' prefix requires the XML namespace.");
73    }
74    if (qname == "xmlns" || prefix == Some("xmlns")) && ns != Some(XMLNS_NS) {
75        return ns_err("The 'xmlns' name requires the XMLNS namespace.");
76    }
77    if ns == Some(XMLNS_NS) && qname != "xmlns" && prefix != Some("xmlns") {
78        return ns_err("The XMLNS namespace requires an 'xmlns' name.");
79    }
80    Ok((ns.map(String::from), prefix.map(String::from), String::from(local)))
81}
82
83/// 引数の名前空間(`null`・`undefined` は無し)。
84pub(crate) fn ns_arg(v: &Value) -> Option<String> {
85    match v {
86        Value::Null | Value::Undefined => None,
87        v => Some(v.to_js_string()),
88    }
89}
90
91/// 検査済みの名前から要素を作る(`owner` は所有文書。`None` は主文書)。
92pub(crate) fn make_element_ns(
93    it: &mut Interp,
94    owner: Option<usize>,
95    ns: Option<String>,
96    prefix: Option<String>,
97    local: &str,
98    qname: &str,
99) -> usize {
100    let is_html = ns.as_deref() == Some(HTML_NS);
101    let idx = if is_html {
102        it.dom().borrow_mut().create_element(local)
103    } else {
104        it.dom().borrow_mut().create_element_plain(local)
105    };
106    {
107        let mut dom = it.dom().borrow_mut();
108        if let Some(n) = dom.nodes.get_mut(idx) {
109            n.attrs.insert(String::from("_qname"), qname.to_string());
110            if !is_html {
111                n.attrs.insert(String::from("_ns"), ns.clone().unwrap_or_default());
112            }
113            if let Some(p) = &prefix {
114                n.attrs.insert(String::from("_prefix"), p.clone());
115            }
116        }
117    }
118    super::dom_doc::note_created(it, owner, idx);
119    if is_html && local.contains('-') && prefix.is_none() {
120        it.ce_try_upgrade(idx, false);
121    }
122    idx
123}
124
125/// `document.createElementNS(namespace, qualifiedName)`。
126pub(crate) fn document_create_element_ns(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
127    let ns = ns_arg(&arg(a, 0));
128    let qname = arg(a, 1).to_js_string();
129    let (ns, prefix, local) = validate_and_extract(it, ns.as_deref(), &qname)?;
130    let owner = super::dom_doc::owner_of_this(it, &t);
131    let idx = make_element_ns(it, owner, ns, prefix, &local, &qname);
132    Ok(it.dom_val(idx))
133}
134
135/// 要素の名前空間 URI(`null` は `None`)。
136pub(crate) use super::super::dom_bridge::node_namespace;
137
138/// `tagName`/`nodeName`: HTML 名前空間の要素は大文字、それ以外は修飾名のまま。
139pub(crate) fn node_tag_name(n: &super::super::dom_bridge::DomNode) -> String {
140    let qname = n.attrs.get("_qname").cloned().unwrap_or_else(|| n.tag.clone());
141    let html = node_namespace(n).as_deref() == Some(HTML_NS);
142    if html && !n.attrs.contains_key("_xml") {
143        qname.to_ascii_uppercase()
144    } else {
145        qname
146    }
147}
148
149pub(crate) use super::super::dom_bridge::node_local_name;
150
151/// `document.getElementsByTagName(qualifiedName)`。
152pub(crate) fn document_get_elements_by_tag_name(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
153    let name = arg(a, 0).to_js_string();
154    let root = this_dom_idx(&t);
155    let include_root = root.is_none();
156    Ok(super::dom::make_live_html_collection(
157        it,
158        crate::os_lib::web_apis::dom_bridge::HtmlCollectionKind::ByTagName {
159            root,
160            include_root,
161            qname: name,
162        },
163    ))
164}
165
166/// `document.getElementsByTagNameNS(namespace, localName)`。
167pub(crate) fn document_get_elements_by_tag_name_ns(it: &mut Interp, t: Value, a: &[Value]) -> Result<Value, Value> {
168    let ns = ns_arg(&arg(a, 0));
169    let local = arg(a, 1).to_js_string();
170    let root = this_dom_idx(&t);
171    let include_root = root.is_none();
172    Ok(super::dom::make_live_html_collection(
173        it,
174        crate::os_lib::web_apis::dom_bridge::HtmlCollectionKind::ByTagNameNS {
175            root,
176            include_root,
177            ns,
178            local,
179        },
180    ))
181}
182
183/// `element.getElementsByTagName(qualifiedName)`。
184pub(crate) fn element_get_elements_by_tag_name(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
185    let name = arg(a, 0).to_js_string();
186    match this_dom_idx(&this) {
187        Some(idx) => Ok(super::dom::make_live_html_collection(
188            it,
189            crate::os_lib::web_apis::dom_bridge::HtmlCollectionKind::ByTagName {
190                root: Some(idx),
191                include_root: false,
192                qname: name,
193            },
194        )),
195        None => Ok(Value::Object(Obj::array(Vec::new()))),
196    }
197}
198
199/// `element.getElementsByTagNameNS(namespace, localName)`。
200pub(crate) fn element_get_elements_by_tag_name_ns(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
201    let ns = ns_arg(&arg(a, 0));
202    let local = arg(a, 1).to_js_string();
203    match this_dom_idx(&this) {
204        Some(idx) => Ok(super::dom::make_live_html_collection(
205            it,
206            crate::os_lib::web_apis::dom_bridge::HtmlCollectionKind::ByTagNameNS {
207                root: Some(idx),
208                include_root: false,
209                ns,
210                local,
211            },
212        )),
213        None => Ok(Value::Object(Obj::array(Vec::new()))),
214    }
215}
216
217// ---- lookupNamespaceURI / lookupPrefix / isDefaultNamespace(DOM Standard §4.4)----
218
219#[derive(PartialEq)]
220enum NsKind {
221    Element,
222    Document,
223    Attr,
224    /// DocumentType・DocumentFragment(常に null)。
225    Inert,
226    /// テキスト・コメント・PI(親の要素で探す)。
227    Other,
228}
229
230fn ns_kind(n: &super::super::dom_bridge::DomNode) -> NsKind {
231    if n.is_text {
232        return NsKind::Other;
233    }
234    match n.tag.as_str() {
235        "#document" => NsKind::Document,
236        "#attr" => NsKind::Attr,
237        "#doctype" | "#fragment" | "#document-fragment" => NsKind::Inert,
238        t if t.starts_with('#') => NsKind::Other,
239        _ => NsKind::Element,
240    }
241}
242
243/// 主文書の `document`(`HostRef(HOST_DOCUMENT)`)か。
244fn is_main_document(v: &Value) -> bool {
245    matches!(v, Value::Object(o) if matches!(&o.borrow().kind, ObjKind::HostRef(h) if h.class == super::super::dom_bridge::HOST_DOCUMENT))
246}
247
248/// `idx` の親にあたる要素(親が要素でなければ `None`)。
249fn parent_element(dom: &super::super::dom_bridge::DomBridge, idx: usize) -> Option<usize> {
250    let p = dom.nodes.get(idx)?.parent?;
251    if ns_kind(dom.nodes.get(p)?) == NsKind::Element {
252        Some(p)
253    } else {
254        None
255    }
256}
257
258/// 文書ノードの documentElement。
259fn document_element(dom: &super::super::dom_bridge::DomBridge, doc: usize) -> Option<usize> {
260    dom.nodes.get(doc)?.children.iter().copied().find(|&c| dom.nodes.get(c).is_some_and(|n| ns_kind(n) == NsKind::Element))
261}
262
263/// 要素の `xmlns` 系の属性を `(接頭辞か None, 値)` で。名前空間が XMLNS のものだけ。
264fn xmlns_attrs(dom: &super::super::dom_bridge::DomBridge, idx: usize) -> Vec<(Option<String>, String)> {
265    let mut out = Vec::new();
266    if let Some(ns_list) = dom.ns_attrs.get(&idx) {
267        for (a_ns, qname, v) in ns_list {
268            if a_ns != XMLNS_NS {
269                continue;
270            }
271            match qname.split_once(':') {
272                Some(("xmlns", l)) => out.push((Some(l.to_string()), v.clone())),
273                None if qname == "xmlns" => out.push((None, v.clone())),
274                _ => {}
275            }
276        }
277    }
278    let Some(n) = dom.nodes.get(idx) else { return out };
279    for name in dom.attr_names(idx) {
280        if n.attrs.get(&format!("_ans:{}", name)).map(|s| s.as_str()) != Some(XMLNS_NS) {
281            continue;
282        }
283        let v = dom.get_attr(idx, &name).unwrap_or_default();
284        match name.split_once(':') {
285            Some(("xmlns", l)) => out.push((Some(l.to_string()), v)),
286            None if name == "xmlns" => out.push((None, v)),
287            _ => {}
288        }
289    }
290    out
291}
292
293fn locate_namespace(dom: &super::super::dom_bridge::DomBridge, start: usize, prefix: Option<&str>) -> Option<String> {
294    let mut cur = start;
295    let mut guard = 0usize;
296    loop {
297        guard += 1;
298        if guard > dom.nodes.len() + 4 {
299            return None;
300        }
301        let n = dom.nodes.get(cur)?;
302        match ns_kind(n) {
303            NsKind::Inert => return None,
304            NsKind::Document => {
305                cur = document_element(dom, cur)?;
306            }
307            NsKind::Attr => {
308                cur = n.attrs.get("_aowner").and_then(|s| s.parse::<usize>().ok())?;
309            }
310            NsKind::Other => {
311                cur = parent_element(dom, cur)?;
312            }
313            NsKind::Element => {
314                let ns = node_namespace(n);
315                let my_prefix = n.attrs.get("_prefix").map(|s| s.as_str());
316                if ns.is_some() && my_prefix == prefix {
317                    return ns;
318                }
319                if prefix == Some("xml") {
320                    return Some(XML_NS.to_string());
321                }
322                if prefix == Some("xmlns") {
323                    return Some(XMLNS_NS.to_string());
324                }
325                for (p, v) in xmlns_attrs(dom, cur) {
326                    if p.as_deref() == prefix {
327                        return if v.is_empty() { None } else { Some(v) };
328                    }
329                }
330                cur = parent_element(dom, cur)?;
331            }
332        }
333    }
334}
335
336fn locate_prefix(dom: &super::super::dom_bridge::DomBridge, start: usize, ns: &str) -> Option<String> {
337    let mut cur = start;
338    let mut guard = 0usize;
339    loop {
340        guard += 1;
341        if guard > dom.nodes.len() + 4 {
342            return None;
343        }
344        let n = dom.nodes.get(cur)?;
345        match ns_kind(n) {
346            NsKind::Inert => return None,
347            NsKind::Document => cur = document_element(dom, cur)?,
348            NsKind::Attr => cur = n.attrs.get("_aowner").and_then(|s| s.parse::<usize>().ok())?,
349            NsKind::Other => cur = parent_element(dom, cur)?,
350            NsKind::Element => {
351                if node_namespace(n).as_deref() == Some(ns) {
352                    if let Some(p) = n.attrs.get("_prefix") {
353                        return Some(p.clone());
354                    }
355                }
356                for (p, v) in xmlns_attrs(dom, cur) {
357                    if let (Some(p), true) = (p, v == ns) {
358                        return Some(p);
359                    }
360                }
361                cur = parent_element(dom, cur)?;
362            }
363        }
364    }
365}
366
367/// 照会の起点(`this` が主文書なら `<html>`)。`Err(())` は起点が無い(null)。
368fn ns_start(it: &Interp, this: &Value) -> Result<usize, ()> {
369    if is_main_document(this) {
370        return if it.dom().borrow().nodes.is_empty() { Err(()) } else { Ok(0) };
371    }
372    this_dom_idx(this).ok_or(())
373}
374
375fn opt_prefix(v: &Value) -> Option<String> {
376    ns_arg(v).filter(|s| !s.is_empty())
377}
378
379pub fn dom_lookup_namespace_uri(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
380    let Ok(start) = ns_start(it, &this) else { return Ok(Value::Null) };
381    let prefix = opt_prefix(&arg(a, 0));
382    let r = locate_namespace(&it.dom().borrow(), start, prefix.as_deref());
383    Ok(r.map(Value::str).unwrap_or(Value::Null))
384}
385
386pub fn dom_lookup_prefix(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
387    let Ok(start) = ns_start(it, &this) else { return Ok(Value::Null) };
388    let Some(ns) = opt_prefix(&arg(a, 0)) else { return Ok(Value::Null) };
389    let r = locate_prefix(&it.dom().borrow(), start, &ns);
390    Ok(r.map(Value::str).unwrap_or(Value::Null))
391}
392
393pub fn dom_is_default_namespace(it: &mut Interp, this: Value, a: &[Value]) -> Result<Value, Value> {
394    let ns = opt_prefix(&arg(a, 0));
395    let Ok(start) = ns_start(it, &this) else { return Ok(Value::Bool(ns.is_none())) };
396    let def = locate_namespace(&it.dom().borrow(), start, None);
397    Ok(Value::Bool(def == ns))
398}