Skip to main content

atmos/os_lib/ecma/
host.rs

1//! ホスト物(`ObjKind::HostRef`)の表。ECMAScript の核はホスト物の中身を知らず、この表の関数を呼ぶだけにする。
2//!
3//! 【2026-11-19 手順 7(`spec/module_boundaries.md` §9)】DOM 要素のハンドルを ECMAScript の核から切り離すための口。
4//! 表は関数ポインタだけの静的な値で、確保も `dyn` も借用も増やさない(呼び出しは間接呼び出し 1 回)。
5//! 実体は `web_apis` 側(今は `interp/host_dom.rs` の `DOM_HOST_HOOKS`)が持つ。差し込みは `JsRuntime::new_interp` の 1 か所。
6//! 段階: 取得(第 3 段)→ 設定・有無・原型・自身のプロパティ・診断(第 4 段)→ 削除・列挙・反復(第 5 段。`style`・`classList`・`dataset`・`storage`・`document` を `HostRef` の種類にした)。
7
8use alloc::rc::Rc;
9use alloc::string::String;
10use alloc::vec::Vec;
11use core::any::Any;
12use core::cell::RefCell;
13
14use super::interp::{Interp, JsRuntime, Scope};
15use super::value::{HostRef, ObjKind, ObjRef, Value};
16
17/// 高速経路(インラインキャッシュ)がホスト物の取得・代入で知りたいこと。
18pub enum HostProbe {
19    /// キャッシュしない(動的に解決する・アクセサがある・特別なキー)。
20    Skip,
21    /// 自身のプロパティの値(取得のときだけ使う。代入のときは `Skip` と同じ扱い)。
22    Own(Value),
23    /// 自身には無く、この原型の連鎖を引く。
24    Proto(Option<ObjRef>),
25}
26
27/// ホスト物の「自身のプロパティ」の状態(`hasOwnProperty`・`getOwnPropertyDescriptor`)。
28pub enum HostOwn {
29    /// 自身のプロパティを実体(`Obj::props`)に持つ種類。核が実体で調べる。
30    Generic,
31    /// 持たない。
32    Absent,
33    /// アクセサ(getter, setter)。
34    Accessor(Option<Value>, Option<Value>),
35    /// データ。
36    Data(Value),
37}
38
39/// ホスト物の自身の列挙可能なプロパティ(`Object.keys` など)。
40pub enum HostKeys {
41    /// 実体(`Obj::props`)に持つ種類。核が実体を列挙する。
42    Generic,
43    /// 列挙できる自身のプロパティは無い(`props` に内部の状態を持つだけ)。
44    Internal,
45    /// 実データはホスト側にある。(キー, 値の文字列) の並び。
46    Entries(Vec<(String, String)>),
47}
48
49pub type HostDefineFn =
50    fn(&mut Interp, HostRef, &str, Option<Value>, Option<Value>, Option<Value>) -> bool;
51pub type HostConstructElementFn =
52    fn(&mut Interp, &Value, &[Value], &Value) -> Option<Result<Value, Value>>;
53
54/// ホスト物に対する操作の表。
55pub struct HostHooks {
56    /// `obj[key]` の取得。`None` は「ホスト物としては処理しない」(核が普通の props・原型の連鎖で解決する)。
57    pub get: fn(&mut Interp, &ObjRef, HostRef, &str) -> Option<Value>,
58    /// `obj[key] = val`。処理したら `None`、処理しなければ値を返す(核が普通の props へ書く)。
59    pub set: fn(&mut Interp, &ObjRef, HostRef, &str, Value) -> Option<Value>,
60    /// `delete obj[key]`。処理したら `Some(結果)`、処理しなければ `None`(核が普通に消す)。
61    pub delete: fn(&mut Interp, HostRef, &str) -> Option<bool>,
62    /// 自身の列挙可能なプロパティ。
63    pub keys: fn(&Interp, HostRef) -> HostKeys,
64    /// `for (x of obj)`(第 3 引数 `true`)・`for (k in obj)`(`false`)の列。ホスト物として扱わなければ `None`。
65    pub iterate: fn(&Interp, HostRef, bool) -> Option<Vec<Value>>,
66    /// `"key" in obj` が「読めるか」で決まる種類か(自身のプロパティを実体に持たず、読み取り時に解決する種類)。
67    pub resolves_on_read: fn(HostRef) -> bool,
68    /// 原型(`__proto__`・`instanceof` の連鎖の起点)。実体の `proto` が無いときだけ使う。
69    /// `None` は「この種類は原型を実体の外に持たない」(核が組み込みの原型へ進む)、`Some(None)` は「原型が無い」。
70    pub proto: fn(&Interp, HostRef) -> Option<Option<ObjRef>>,
71    /// `__proto__` への代入。処理したら `true`。
72    pub set_proto: fn(&mut Interp, HostRef, &ObjRef) -> bool,
73    /// インラインキャッシュ用の問い合わせ。第 3 引数は代入のとき `true`。
74    pub probe: fn(&Interp, HostRef, &str, bool) -> HostProbe,
75    /// 自身のプロパティの状態。
76    pub own: fn(&Interp, HostRef, &str) -> HostOwn,
77    /// `Object.defineProperty` の自身のプロパティ(get, set, value の順)。処理したら `true`。
78    pub define: HostDefineFn,
79    /// 診断用の短い説明(`<div#player.x>`)。無ければ `None`。
80    pub describe: fn(&Interp, HostRef) -> Option<String>,
81    /// 種類名(診断用の短い名, 呼べない物としての名)。
82    pub class_name: fn(HostRef) -> (&'static str, &'static str),
83    /// カスタム要素(`HTMLElement` 等)の `new` 構築。対象外なら `None`。
84    pub construct_element: HostConstructElementFn,
85    /// 循環 GC 前のホスト資源掃除(孤立 DOM ノードの解放など)。
86    pub gc_cleanup: fn(&Interp),
87    /// 関数呼び出し後の後処理(カスタム要素の反応キュー消化など)。
88    pub after_call: fn(&mut Interp),
89    /// `JsRuntime::host_state` から `Interp::host_state` を作る。
90    pub new_interp_state: fn(&dyn Any) -> Rc<dyn Any>,
91    /// `JsRuntime::new` の初期化末尾(prelude の仕掛け等)。
92    pub init_runtime: fn(&mut JsRuntime),
93    /// `Drop for JsRuntime` の片付け(ホスト資源から循環根を回収し、外部資源を解放する)。
94    pub teardown_runtime: fn(u64, &dyn Any, &mut Vec<Value>),
95    /// 現在の文書 URL(`location.href` 等)。無ければ `None`(`JsRuntime::base_url` を使う)。
96    pub current_base_url: fn(&Rc<RefCell<Scope>>) -> Option<String>,
97    /// 到着済みの非同期 I/O 結果があるか(`JsRuntime::host_state` を受ける)。
98    pub has_ready_async_io: fn(&dyn Any) -> bool,
99    /// 未完了の非同期 I/O があるか(`Interp::host_state` を受ける)。
100    pub has_pending_async_io: fn(&dyn Any) -> bool,
101    /// 到着済みの非同期 I/O 結果を配送する。1 件以上処理したら `true`。
102    pub pump_async_io: fn(&mut Interp) -> bool,
103    /// `JsRuntime::eval` 末尾の後処理(Observer 発火など)。
104    pub after_eval: fn(&mut Interp),
105    /// `JsRuntime::pump_timers` 末尾の後処理(MutationObserver 発火など)。
106    pub after_pump: fn(&mut Interp),
107    /// 非 `HostRef` のホスト特殊実体(`RadioNodeList.value` / `select.selectedIndex` 等)の取得。対象外なら `None`。
108    pub special_get: fn(&mut Interp, &ObjRef, &str) -> Option<Value>,
109    /// 非 `HostRef` のホスト特殊実体への代入。処理したら `true`。
110    pub special_set: fn(&mut Interp, &ObjRef, &str, &Value) -> bool,
111}
112
113/// 何もしない既定のホスト表(DOM・Web API 無しの純粋 ECMAScript 実行用)。
114pub static NULL_HOST_HOOKS: HostHooks = HostHooks {
115    get: |_, _, _, _| None,
116    set: |_, _, _, _, v| Some(v),
117    delete: |_, _, _| None,
118    keys: |_, _| HostKeys::Generic,
119    iterate: |_, _, _| None,
120    resolves_on_read: |_| false,
121    proto: |_, _| None,
122    set_proto: |_, _, _| false,
123    probe: |_, _, _, _| HostProbe::Skip,
124    own: |_, _, _| HostOwn::Generic,
125    define: |_, _, _, _, _, _| false,
126    describe: |_, _| None,
127    class_name: |_| ("host", "host object"),
128    construct_element: |_, _, _, _| None,
129    gc_cleanup: |_| {},
130    after_call: |_| {},
131    new_interp_state: |_| Rc::new(()),
132    init_runtime: |_| {},
133    teardown_runtime: |_, _, _| {},
134    current_base_url: |_| None,
135    has_ready_async_io: |_| false,
136    has_pending_async_io: |_| false,
137    pump_async_io: |_| false,
138    after_eval: |_| {},
139    after_pump: |_| {},
140    special_get: |_, _, _| None,
141    special_set: |_, _, _, _| false,
142};
143
144impl Interp {
145    /// ホスト物のプロパティを取得する。`None` なら核が普通の解決を続ける。
146    #[inline]
147    pub(crate) fn host_get(&mut self, o: &ObjRef, h: HostRef, key: &str) -> Option<Value> {
148        (self.host.get)(self, o, h, key)
149    }
150}
151
152impl Interp {
153    /// 実体に原型が無いホスト物の原型(`HostHooks::proto` の包み。ホスト物でなければ `None`)。
154    #[inline]
155    pub(crate) fn host_proto_of(&self, kind: &ObjKind) -> Option<Option<ObjRef>> {
156        if matches!(kind, ObjKind::RegExpObj(_)) {
157            // 正規表現は原型を持たせずに作る(`Obj::regexp`)。原型の連鎖は `RegExp.prototype` から始まる。
158            return Some(super::builtins::global_ctor_proto(self, "RegExp"));
159        }
160        kind.host_ref().and_then(|h| (self.host.proto)(self, h))
161    }
162}
163
164impl Interp {
165    /// 自身の列挙可能なプロパティの所在(`Object.keys` など)。ホスト物と、ECMAScript の内部の物(`Iter`・`GenReturn`)を見分ける。
166    #[inline]
167    pub(crate) fn host_keys_of(&self, kind: &ObjKind) -> HostKeys {
168        match kind {
169            ObjKind::HostRef(h) => (self.host.keys)(self, *h),
170            ObjKind::Iter | ObjKind::GenReturn => HostKeys::Internal,
171            _ => HostKeys::Generic,
172        }
173    }
174}